开发者

Explaining hashcode to Vector

Can I get an idea of how the hashcode takes the valueas per the element added to vector?

  Vector v = new Vector();

  //Add elements to Vector
  v.add("1");
  System.out.println(v.hashCode());
  v.add("2");
  System.out.println(v.hashCode());
  v.add("=");
  System.开发者_开发问答out.println(v.hashCode());

The hashcode values are

 80
 2530
 78491


It works the same for every (true) implementation of the List interface (if it supports adding elements). The behavior of the .hashCode method is defined in List.hashCode() as follows:

Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:

 int hashCode = 1;
 Iterator<E> i = list.iterator();
 while (i.hasNext()) {
     E obj = i.next();
     hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
 }

This ensures that list1.equals(list2) implies that list1.hashCode()==list2.hashCode() for any two lists, list1 and list2, as required by the general contract of Object.hashCode().

As glowcoder showed, AbstractList contains just this implementation, and thus not every implementor of the List interface has to do this again.

For example, you also could write Arrays.asList("1", "2").hashCode() and would get the same 2530 (as long as you don't change the hashCode() implementation of String).


Because Vector extends AbstractList, it uses it for it's hashCode. Here's what it does.

public int hashCode() {
int hashCode = 1;
Iterator<E> i = iterator();
while (i.hasNext()) {
    E obj = i.next();
    hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
return hashCode;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜