Search code examples
javacollectionsvectorhashcodejava-6

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

Solution

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