how to make a set of array in java?

前端 未结 5 1572
醉梦人生
醉梦人生 2020-12-22 11:29

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

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-22 12:13

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

提交回复
热议问题