Automation Using Selenium Webdriver
Showing posts with label List and set exampls. Show all posts
Showing posts with label List and set exampls. Show all posts

Wednesday 3 August 2016

List and set

Difference between List and Set in Java::
------------------------------------------------
List and Set both are interfaces. They both extends Collection interface. In this post we are discussing the differences between List and Set interfaces in java.

List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.

 List implementations: ArrayList, LinkedList etc.
 
 Set implementations: HashSet, LinkedHashSet, TreeSet etc.

EX: List

public class ListExample {

 public static void main(String[] args) {
   List<String> al = new ArrayList<String>();
   al.add("Chaitanya");
   al.add("Rahul");
   al.add("Ajeet");
   System.out.println("ArrayList Elements: ");
   System.out.print(al);

   List<String> ll = new LinkedList<String>();
   ll.add("Kevin");
   ll.add("Peter");
   ll.add("Kate");
   System.out.println("\nLinkedList Elements: ");
   System.out.print(ll);
 }
}

Output:
ArrayList Elements:
[Chaitanya, Rahul, Ajeet]
LinkedList Elements:
[Kevin, Peter, Kate]

Set Example:

public class SetExample {

  public static void main(String args[]) {
    int count[] = {11, 22, 33, 44, 55};
    Set<Integer> hset = new HashSet<Integer>();
    try{
      for(int i = 0; i<4; i++){
         hset.add(count[i]);
      }
      System.out.println(hset);

      TreeSet<Integer> treeset = new TreeSet<Integer>(hset);
      System.out.println("The sorted list is:");
      System.out.println(treeset);
    }
    catch(Exception e){
        e.printStackTrace();
    }
  }

Output:
[33, 22, 11, 44]
The sorted list is:
[11, 22, 33, 44]