集合类的equals方法(惊天大发现)

tech2022-10-14  116

List集合类

Returns the hash code value for this list. The hash code of a list * is defined to be the result of the following calculation: * <pre>{@code * int hashCode = 1; * for (E e : list) * hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); * }</pre>

可以看到,如果集合里面的值相同,那么集合对象equals会返回true!

 

Set集合类

* Returns the hash code value for this set. The hash code of a set is * defined to be the sum of the hash codes of the elements in the set

可以看到,如果集合里面的值相同,那么集合对象equals会返回true!

 

Map集合类

* Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * Returns the hash code value for this map entry. The hash code * of a map entry <tt>e</tt> is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode())

可以看到,如果key和key相同、value和value相同,那么集合对象equals会返回true!

 

通过上面可以知道,集合类重写了equals方法,比较的是元素的hashcode值,只要集合类中元素的值相同,那么两个集合类的equals方法就会返回true!

最新回复(0)