how to make a set of array in java?

前端 未结 5 1559
醉梦人生
醉梦人生 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 {
    
        @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 extends ArrayList {
        //overrides the methods you need
        @Override
        public boolean equals(Object o) {
            if (o instanceof MyArrayList) {
                //place your comparison logic here
                return true;
            }
            return false;
        }
    }
    

提交回复
热议问题