Tuesday 27 May 2014

LinkedList : equals : Compare two lists for Equality

public boolean equals(Object o)
Two lists are defined to be equal if they contain the same elements in the same order. Methods equals, hashCode, listIterator, removeRange, subList are inherited from AbstractList.

import java.util.*;

class LinkedListEquals{
 public static void main(String args[]){
  LinkedList<Integer> myList1 = new LinkedList<> ();
  LinkedList<Integer> myList2 = new LinkedList<> ();
  LinkedList<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("Is myList1 and myList3 are Equal " + myList1.equals(myList3));
  System.out.println("Is myList2 and myList3 are Equal " + myList2.equals(myList3));
 }
}

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
Is myList1 and myList3 are Equal false
Is myList2 and myList3 are Equal false

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment