how to make a set of array in java?

2020-02-16 03:30发布

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?

标签: java arrays set
5条回答
别忘想泡老子
2楼-- · 2020-02-16 04:17

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楼-- · 2020-02-16 04:18

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;
    }
}
查看更多
女痞
4楼-- · 2020-02-16 04:18

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楼-- · 2020-02-16 04:18

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

查看更多
欢心
6楼-- · 2020-02-16 04:19

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

查看更多
登录 后发表回答