How can I get a collection of unique pairs of values in Java?
I read this other posting and tried the following code from an answer to that posting as a Pair
class:
public class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
But how to I ensure that a collection of Pair
objects only contains unique combinations of left
+right
using the Pair
class?
Here is my first attempt:
sel_person = this.serviceLayer.findSelPerson(patntId);
ArrayList<Pair> ps = new ArrayList<Pair>();
for(int ee=0;ee<sel_person.getRoles().size();ee++){
Pair p1 = new Pair(sel_person.getRoles().get(ee).getId1Root(), sel_person.getRoles().get(ee).getId1Extension());
ps.add(p1);
Pair p2 = new Pair(sel_person.getRoles().get(ee).getId2Root(), sel_person.getRoles().get(ee).getId2Extension());
ps.add(p2);
}
My fear is that the ArrayList
will not care if there are redundant combinations of left
+right
. I wonder if the hashcode
method will somehow prevent instantiation of Pair
objects with redundant combinations of left
+right`, but how can I be sure? If the above code is correct, then a good answer would simply explain why. If something else needs to be done, then a good answer would explain what else needs to be done.