Thursday, June 23, 2016

Set interface


This is another core interface in java collection hierarchy. Special thing is Set cannot contain duplicates. Set has three main implements.

  1. java.util.TreeSet
  2. java.util.HashSet
  3. java.util.LinekedHashSet

Common characteristics

  • No duplicates
  • Not thread safe

Other characteristics

  • HashSet is the fastest set implementation, TreeSet is slowest one.
  • HashSet doesn't maintain a order. But LinkedHashSet maintain insertion order while TreeSet maintain sorted order because it implements sortedSet interface.
  • Both HashSet and LinkedHashSet allow null values but TreeSet doesn't allow null values.
  • LinkedHashSet was introduced in 1.4 version in Java.

TreeSet vs HashSet vs LinkedHashSet




Look at the following example to understand about Treeset. It shows about sorting of TreeSet. 

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {

   public static void main(String[] args) {
  
       Set<Integer> treeSet = new TreeSet<>();
  
       treeSet.add(30);
       treeSet.add(10);
       treeSet.add(50);
       System.out.println(treeSet);
   } 
}



Look at the following example to get a brief idea about set interface.

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {

   public static void main(String[] args) {
  
       Set<Integer> treeSet = new TreeSet<>();

  
       treeSet.add(30);
       treeSet.add(10);
       treeSet.add(50);
       System.out.println(treeSet);
  
       System.out.println(treeSet.size());
       System.out.println(treeSet.isEmpty());
       System.out.println(treeSet.contains(500));
       System.out.println(treeSet.remove(10));
       System.out.println(treeSet.equals(50));
       treeSet.clear();
       System.out.println(treeSet);
   }
}



Look at the following example to get an idea about the things that you can do with sets. Following example shows to get distinct characters.

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {

   public static void main(String[] args) {
  
       Set set = new TreeSet<>();
  
       String s = "This is a set interface";
       String []arr = s.split("");
  
       for(String i : arr){
           set.add(i);
       }
  
       System.out.println(set);
   }
}