Tuesday 1 April 2014

equals : Compare two lists

boolean equals(Object o)
   Two lists are defined to be equal if they contain the same elements in the same order.

import java.util.*;

class ListEquals{
 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("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