Tuesday 1 April 2014

hashCode of the List

int hashCode()
   Returns the hash code value for this list. If two lists are equal, then their hash codes also equal.

import java.util.*;

class ListHashCode{
 public static void main(String args[]){
  List<Integer> myList1 = new ArrayList<> ();
  List<Integer> myList2 = new LinkedList<> ();
  List<Integer> myList3 = new LinkedList<> ();
  
  /* Add Elements to myList1 and myList2*/
  for(int i=0; i<10; i++){
   myList1.add(i);
   myList2.add(i);
  }
  
  /* Add Elements to myList3 */
  for(int i=9; i>-1; i--){
   myList3.add(i);
  }
  
  /*Display Elements in the lists */
  System.out.println("Elements in myList1 are \n" + myList1);
  System.out.println("\nElements in myList2 are \n" + myList2);
  System.out.println("\nElements in myList3 are \n" + myList3);
  
  System.out.println("\nIs myList1 and myList2 are Equal " + myList1.equals(myList2));
  System.out.println("myList1 hashCode is " + myList1.hashCode());
  System.out.println("myList2 hashCode is " + myList2.hashCode());
  
  System.out.println("\nIs myList1 and myList3 are Equal " + myList1.equals(myList3));
  System.out.println("myList1 hashCode is " + myList1.hashCode());
  System.out.println("myList3 hashCode is " + myList3.hashCode());
  
  System.out.println("\nIs myList2 and myList3 are Equal " + myList2.equals(myList3));
  System.out.println("myList2 hashCode is " + myList2.hashCode());
  System.out.println("myList3 hashCode is " + myList3.hashCode());
 }
}

Output
Elements in myList1 are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Elements in myList2 are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Elements in myList3 are
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Is myList1 and myList2 are Equal true
myList1 hashCode is -1631921466
myList2 hashCode is -1631921466

Is myList1 and myList3 are Equal false
myList1 hashCode is -1631921466
myList3 hashCode is -353583012

Is myList2 and myList3 are Equal false
myList2 hashCode is -1631921466
myList3 hashCode is -353583012








Prevoius                                                 Next                                                 Home

No comments:

Post a Comment