Reputation: 4815
I have written a simple test program in which I am trying to store unique pair of (String,String). Here below I mentioned my code part:
public class Pair {
private String cr_ts_hi;
private String cr_ts_lo;
//constructor and getter-setter
}
class Test{
private static HashSet<Pair> caseExceptionReport = new LinkedHashSet<Pair>();
public static void main(String[] args) {
caseExceptionReport.add(new Pair("abc","itm1"));caseExceptionReport.add(new Pair("abc","itm2"));
caseExceptionReport.add(new Pair("abc","itm1"));caseExceptionReport.add(new Pair("def","itm1"));
caseExceptionReport.add(new Pair("def","itm2"));caseExceptionReport.add(new Pair("def","itm2"));
caseExceptionReport.add(new Pair("xyz","itm1"));caseExceptionReport.add(new Pair("xyz","itm2"));
for(Pair m:caseExceptionReport){
System.out.println(m.getCr_ts_hi() + " *** " + m.getCr_ts_lo());
}
}
And output is:
abc *** item1
abc *** item2
abc *** item1
def *** item1
def *** item2
def *** item2
xyz *** item1
xyz *** item2
Expected output is:
abc *** item1
abc *** item2
def *** item1
def *** item2
xyz *** item1
xyz *** item2
I am not getting a way to store unique pairs. I though HashSet won't allow duplicate Pair's but it is not working. Any other idea for this?
Upvotes: 2
Views: 2500
Reputation: 3460
You need to define the equality of the Pair
public class Pair {
private String cr_ts_hi;
private String cr_ts_lo;
//constructor and getter-setter
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (cr_ts_hi != null ? !cr_ts_hi.equals(pair.cr_ts_hi) : pair.cr_ts_hi != null) return false;
return cr_ts_lo != null ? cr_ts_lo.equals(pair.cr_ts_lo) : pair.cr_ts_lo == null;
}
@Override
public int hashCode() {
int result = cr_ts_hi != null ? cr_ts_hi.hashCode() : 0;
result = 31 * result + (cr_ts_lo != null ? cr_ts_lo.hashCode() : 0);
return result;
}
}
Upvotes: 1
Reputation: 46
You need to override hashCode() and equals() otherwise you're defaulting to Object's implementation.
See: docs.
Upvotes: 1
Reputation: 18208
You need to override the equals() and hashCode() methods in your Pair class. Please follow the below related link for details:
HashSet does not seem to realize that two objects are the same
Upvotes: 1