java - make sure a list has unique values -


how can collection of unique pairs of values in java?

i read this other posting , tried following code answer posting 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 ensure collection of pair objects contains unique combinations of left+right using pair class?

here 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 arraylist not care if there redundant combinations of left+right. wonder if hashcode method somehow prevent instantiation of pair objects redundant combinations of left+right`, how can sure? if above code correct, answer explain why. if else needs done, answer explain else needs done.

but how ensure collection of pair objects contains unique combinations of left+right using pair class?

a list cares not duplicate elements. implementation of set interface (for instance hashset) more appropriate, set defined collection of unique elements (uniqueness defined hashcode , equals of objects contains).

set<pair> ps = new hashset<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); } //now ps has unique pairs defined pair class hashcode/equals 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -