Good evening. I'm working with an arraylist, and I had to make sure no duplicate objects were inserted. My object has an array [5] [5] which is the main element that I need to ensure is not repeated. Anyone have any suggestions?
Good evening. I'm working with an arraylist, and I had to make sure no duplicate objects were inserted. My object has an array [5] [5] which is the main element that I need to ensure is not repeated. Anyone have any suggestions?
It's not clear where you're headed, but I'll try to respond with what I've understood so far:
If you can not have repeated elements, a Set
(set) is the most appropriate data structure. It remains to know which set is best for you.
If your elements can be placed in a total order, then TreeSet
is the most suitable: not only does it guarantee uniqueness but also keeps your elements in order:
Comparator<int[][]> c = new Comparator<int[][]>() {
public int compare(int[][] a, int[][] b) {
...
}
};
TreeSet<int[][]> c = new TreeSet<int[][]>(c);
Otherwise, a HashSet
is more appropriate. However, comparing arrays in Java is done by reference, not by value. If you want content of the arrays to be compared, you must use a wrapper object that makes use of deepEquals
deepHashCode
:
class MeuObjeto {
private int[][] array;
public boolean equals(Object o) {
if ( o instanceof MeuObjeto )
return Arrays.deepEquals(this.array, ((MeuObjeto)o).array);
else
return false;
}
pubilc int hashCode() {
return Arrays.deepHashCode(array);
}
}
HashSet<MeuObjeto> c = new HashSet<MeuObjeto>();
Finally, if you want to use HashSet
but would like the elements to be returned in the same order as they were entered, you can use LinkedHashSet
instead. The example is identical to the previous item, it just changes the class.