For a HashMap that maps from a custom class, how do I make two equivalent keys display a value?

I have a custom class, for example, let sake say that it is not ordered.

public class UnorderedTuple {  
    Integer i1 = null; Integer i2 = null;

    UnorderedTuple(Integer int1, Integer int2) { i1 = int1; i2 = int2; }

    boolean equals(UnorderedTuple t) { return t.i1 == i1 && t.i2 == t2 || t.i2 == i1 && t.i1 == i2; }
}

As I said, a dumb example. Now let's say I have

Map<UnorderedTuple, Integer> m = new HashMap<UnorderedTuple, Integer>();

Ideally, I would like to take advantage of this functionality:

UnorderedTuple ut1 = new UnorderedTuple(1,2);
UnorderedTuple ut2 = new UnorderedTuple(2,1);

m.put(ut1,2);
m.put(ut2,3);
System.out.println(m.get(ut1)==3); //ideally returns true

Is there something I need to implement or expand so that I have such functionality? Similarly, if you use 2 different but equal strings or integers or something as a key, it will display it correctly, but if I implement it as written, it processes ut1 and ut2 separately. Even if I build ut1 and ut2 identically, it does the same.

Thank you for your help.

+3
source share
5

hashCode()... , , , XORing - , .

equals(Object), equals(UnorderedTuple).

, "==" Integer: . , - , 127, - , . equals .

+18

hashCode() , equals() ( , a.equals(b) true, a.hashCode() == b.hashCode() true).

3 Java ( PDF!) !

: , equals(Object). equals(UnorderedTuple), !

+4

equals() hashCode()? . javadoc

+2
+1

-, . , , , - -.

0

Source: https://habr.com/ru/post/1787713/


All Articles