I am novice to java. I have an ArrayList
and I want to avoid duplicates on insertion. My ArrayList
is
ArrayList karList
Use a HashSet
instead of an ArrayList
. But, to really make the HashSet
really work well, you must override the equals()
and hashCode()
methods of the class/objects that are inserted into the HashSet
.
Foe example:
Set set = new HashSet();
set.add(foo);
set.add(bar);
public class MyObject {
@Override
public boolean equals(Object obj) {
if (obj instanceof MyObject)
return (this.id = obj.id)
else
return false;
}
// now override hashCode()
}
Please see the following documentation for overriding hashCode()
and equals()
.