how to make a set of array in java?

前端 未结 5 1539
醉梦人生
醉梦人生 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:11

    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;
        }
    }
    
    0 讨论(0)
  • 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;
    }   
    }
    
    0 讨论(0)
  • 2020-12-22 12:29

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

    0 讨论(0)
  • 2020-12-22 12:30

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

    0 讨论(0)
  • 2020-12-22 12:31

    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.

    0 讨论(0)
提交回复
热议问题