Tuesday 20 December 2016

Difference : List Vs Set

List and Set differs based on the following parameters.

1.       Duplicate Object
List allows duplicate elements to be stored in it.
Set doesn’t allow duplicate element. All the element needs to be unique.

2.       Order Maintenance
List generally maintains the insertion order.
In set maintenance of insertion order depends on the implementing class. (HashSet-> order not guaranteed, LinkedHashSet-> Order is maintained)

3.       Null value
In List, one can store unlimited null values
In Set, only one null value is permitted.

4.       Implementations
ArrayList class, LinkedList class and Vector class implements List interface.
HashSet class, LinkedHashSet class and TreeSet class implements Set interface.

5.       Traversal
You can use both ListIterator and Iterator to traverse elements in List.
You cannot use ListIterator to iterate Set. To traverse Set use Iterator.

Example

package collection;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListandSet {

      public static void main(String[] args) {
            List<String> arrayList = new ArrayList<String>();
            arrayList.add("A");
            arrayList.add("B");
            arrayList.add("A");
            arrayList.add("C");
            arrayList.add("D");
            System.out.println("List elements:"+ arrayList);
           
            Set<String> set = new HashSet<String>();
            set.add("A");
            set.add("B");
            set.add("A");
            set.add("C");
            set.add("D");
            System.out.println("Set elements:"+ set);

      }


}

Output:
List elements:[A, B, A, C, D]
Set elements:[A, B, C, D]

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.