how to make a set of array in java?

2020-02-16 03:50发布

问题:

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 could be put each array in an object, and implement equals function for that class, but will that decrease the performance too much?

回答1:

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;
    }
}


回答2:

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.



回答3:

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).



回答4:

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;
}   
}


回答5:

A class that extends Set and override the equals method could do it.



标签: java arrays set