Я написал следующий код для парного класса в Java с помощью map.Entry. У кого -нибудь есть рекомендации по его улучшению? Наиболее важным для меня критерием, которым необходимо соответствовать классу, было то, что было бы легко построить пару, и что. Эквалы будут работать так, как я хотел (равенство двух объектов в паре в том же порядке означает равенство пар). Код, по -видимому, функционирует как предполагаемый и не используется во всем, что налогодит памяти моей системы, но любые оптимизации будут оценены. < /P>
import java.util.*;
public class Pair {
// Return a map entry (key-value pair) from the specified values
public static Map.Entry of(T first, U second) {
return new AbstractMap.SimpleEntry(first, second);
}
private Map.Entry entry;
public Pair (Object x, Object y) {
Set entries = new HashSet();
entries.add(Pair.of(x, y));
Object[] setArray = entries.toArray();
this.entry = (Map.Entry) setArray[0];
}
public Object getKey() {
return entry.getKey();
}
public Object getValue() {
return entry.getValue();
}
@Override
public boolean equals(Object o)
{
if (o instanceof Pair) {
Pair pair = (Pair) o;
return ( (entry.getKey().equals(pair.getKey())) && (entry.getValue().equals(pair.getValue())) );
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(entry.getKey(), entry.getValue());
}
@Override
public String toString() {
return String.format( "(" +entry.getKey().toString() + ", " + entry.getValue().toString() + ")" );
}
}
< /code>
Я рассматривал возможность использования collections.singletonmap вместо map.entry. < /p>
Пока я успешно протестировал свой код, используя следующее: < /p>
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap testMap = new HashMap();
Pair onThrup = new Pair(1, 3);
System.out.println(onThrup); //Prints contents of Pair, not hash
testMap.put(onThrup, 7);
Pair unoTres = new Pair(1, 3);
System.out.println(onThrup.equals(unoTres));
System.out.println(testMap.containsKey(onThrup));
System.out.println(unoTres.hashCode() == onThrup.hashCode());
System.out.println(testMap.containsKey(unoTres)); // Should be, and is, true
}
}
Подробнее здесь: https://stackoverflow.com/questions/677 ... ss-in-java