I have a class Test with attributes
--> Integer id1
--> Integer id2
--> String stringValue.
So there are list of stringValues per (id1 and id2) combination of unique ids. I want to be able store that in a collection. Example:
test1 : id1 = 1, id2 = 2 , stringValue = one
test11 : id1 = 1, id2 = 2 , stringValues =two
test111 : id1 = 1, id2 = 3 , stringValues =three
test2 : id1 = 5, id2 = 3, stringValues = four
test22: id1 = 5, id2 = 2, stringValues = five
test222: id = 5, id2 = 3, stringValues = six
Desired end result is store the objects as
-> {id = 1, id = 2, String = {one, two} }
-> {id = 1 , id =3 , String = {three}}
-> {id = 5, id = 3 , String = {four,six}}
-> {id = 5, id = 2 , String = {five}}
I want to be able to store the list of 'test' objects in a collection. I tried Set<> , overriding the equals and hashcode but it didnt work as expected. Here you go
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id1 == null) ? 0 : id1.hashCode());
result = prime * result + ((id2 == null) ? 0 : id2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if( obj instanceof Test){
Test test = (Test) obj;
return (test.id1 == this.id1 && test.id2 == this.id2);
} else {
return false;
}
}
I loop through each object and store it in a SET. it does eliminate (redundant combination of [id1 and id2], but it also eliminates the respective string value.) Oops I forgot to mention I get the data from a resultset retrieved from database. so each row consists of id1, id2 and a string value(which is different for all rows). some rows will have a common id1 and id2 values
Can someone please suggest me with any pointers please ?
Thank you in advance