hashCode() for an array of objects for use in HashMap

前端 未结 2 1281
别那么骄傲
别那么骄傲 2020-12-22 04:26

I Have the following two classes and want to use Foo1 as keys in a HashMap. Two Foo1 objects are equal if their Foo2 obj

2条回答
  •  一向
    一向 (楼主)
    2020-12-22 05:24

    Your hashcode should use the same set of properties as equals for it not to break the contract.

    Just use the Arrays.hashcode as done in Foo2

    Also you dont have to loop through each element in your equals you can just use Arrays.equals

    Foo2 equals can look like this similar to Foo1.equals

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Foo1 other = (Foo1) obj;
            if (!Arrays.equals(foo2_array, other.foo2_array))
                return false;
            return true;
        }
    

    and hashcode similar to Foo1 hashcode

        @Override
        public int hashCode() {
            return Arrays.hashCode(foo2_array);
        }
    

    Also while implementing equals do check for same reference and object validity for null.

提交回复
热议问题