Since the equals function in array only check the instance, it doesn\'t work well with Set. Hence, I wonder how to make a set of arrays in java?
One possible way cou
Since the ArrayList class already wraps an array, you can extend it and override the equals
and hashCode
methods. Here is a sample:
public MyArrayList extends ArrayList<MyClass> {
@Override
public boolean equals(Object o) {
if (o instanceof MyArrayList) {
//place your comparison logic here
return true;
}
return false;
}
@Override
public int hashCode() {
//just a sample, you can place your own code
return super.hashCode();
}
}
UPDATE:
You can even override it for a generic use, just changing the code to:
public MyArrayList<T> extends ArrayList<T> {
//overrides the methods you need
@Override
public boolean equals(Object o) {
if (o instanceof MyArrayList) {
//place your comparison logic here
return true;
}
return false;
}
}
You could create a wrapper class for your array and override hashcode and equals accordingly. For example:
public class MyArrayContainer {
int[] myArray = new int[100];
@Override
public boolean equals(Object other) {
if (null!= other && other instanceof MyArrayContainer){
MyArrayContainer o = (MyArrayContainer) other;
final int myLength = myArray.length;
if (o.myArray.length != myLength){
return false;
}
for (int i = 0; i < myLength; i++){
if (myArray[i] != o.myArray[i]){
return false;
}
}
return true;
}
return false;
}
@Override
public int hashCode() {
return myArray.length;
}
}
A class that extends Set and override the equals method could do it.
If you make your Set be an instance of TreeSet, you can specify a custom Comparator which will be used for all comparisons (even equality).
Don't use raw Arrays unless you absolutely have to because of some legacy API that requires an Array.
Always try and use a type safe ArrayList<T>
instead and you won't have these kind of issues.