INTRODUCTION OF SET, HASHSET AND LINKEDHASHSET

Introduction Of Set


Set

  • The set is sub interface of collection in colletions framework.It is again divided into three types. The following shows set interface hierarchy.

  • Naming Convention
    SET

  • All set interface doesn’t support random access for retrieving so it won’t supports index based operation. It means in Set interface there is no index based method like List interface.

  • For example in List interface the methods are addAll(index , value), remove( ), removeAll( ), get(index).these methods works based on index values only.

  • For example in List interface the methods are addAll(index , value), remove( ), removeAll( ), get(index).these methods works based on index values only.

  • But in set interface it won’t support or contain get( ) method also..

  • Set interface won’t allows duplicate values also.

  • Set interface won’t give ordered output why because here there is no index based iteration we should iterate through the Iterator interface (or) ListIterator interface there is no other way.

  • Set interface won’t support collections.sort( ) method it is exclusively for list interface only.

  • Set interface allows null values only one time.

  • In set interface if we try to add same element more than one time we won’t get any errors but it will consider only element from those which is added at last.

  • In set there is no specific classes for thread safety like vector in List interface.

  • If we want to secure any set object then we should use collections.synchronizedSet( ) .

  • There is some methods in collection class for providing external thread safety for any collection object.

  • example:

      1. Collections.synchronizedSet(Set set);
      2. Collections.synchronizedList(List list);
      3. Collections.synchronizedMap(Map map);
      3. Collections.synchronizedCollection(Collection col);
    • By using the external synchronization for set,list,map we use above syntax.

HashSet:

  • HashSet is one of the import class in set interface. It is under java.utils package.

  • HashSet is used if we have requirement to avoid the duplicate elements means HashSet also won’t allow duplicate values why because this class implements the Set interface.

  • The three main operations in set are

    • Adding.

    • Reading/Iterate.

    • Remove.

Adding operation:

  • The following example shows add elements to set through add(object obj) method.

Example 1:

 
            
              package com.sdj.pack1;
              public class HashSetExmpl
              {
                 public static void main(String[] args)
                 {
                    HashSet set=new HashSet();
                    set.add("10");
                    set.add("20");
                    set.add("65");
                    set.add("45");
                    set.add("20");
                    set.add("45");
                    set.add("100");
                    System.out.println("adding elements to set:"+set);
                 }
              } 
                

Output:

Adding elements to set : [ 65, 10, 20, 100, 45]
    Note
    • There is no guarantee for the same order of output. If we run many times the output will may come in same order or not there is no guarantee.
    • The set interface won’t allow duplicate values. If we are trying to add duplicate values it won’t consider but it won’t take last added values as output.
    • Here in the above example we are trying to add “20” & “45” values again but it won’t take them.
    • Inside set interface the toString( ) method get overrided.
    • If we add set values to same set in above example through add( ) method is likeset.add(set);

Output:

     Adding elements to set:[ 65, 10, (this Collection), 20, 100, 45]
  • We can add one set values to another set also. The following example adds one set to another

Example 2: How to add one set to another set

 
            
              package com.sdj.pack1;
              public class HashSetExmpl
              {
                 public static void main(String[] args)
                 {
                    HashSet set=new HashSet();
                    set.add("10");
                    set.add("30");
                    set.add("65");
                    set.add("35");
                    set.add("100");
                    set.add(set);
                    System.out.println(" set elements are:"+set);
                    HashSet set1=new HashSet();
                    set1.add(45);
                    set1.add("70");
                    System.out.println(“set1 elements are:”+set1);
                    set.add(set1);
                    System.out.println("set elements are:"+set);
                 }
              } 
                   

Output:

set elements are:[65, 10, 35, 30, 100, (this Collection)] set1 elements are:[70, 45] After adding set1 to set elements are:[65, 10, 35, 30, [45, 70], 100, (this Collection)]

How to add list interface to set interface:

  • It is possible to add one list interface also to the set interface is shown in below example .

Example 3:

 
            
              package com.sdj.pack1;
              public class HashSetExmpl
              {
                 public static void main(String[] args)
                 {
                    HashSet set=new HashSet();
                    set.add("10");
                    set.add("30");
                    set.add("65");
                    set.add("35");
                    set.add("100");
                    set.add(set);
                    System.out.println(" set elements are:"+set);
                    List l1=new ArrayList();
                    l1.add(20);
                    l1.add("SDJ");
                    l1.add("ajeet");
                    System.out.println("list elements are:"+l1);
                    l1.addAll(set);
                    System.out.println("set elements add to list:"+l1);
                 }
              } 
                   

Output:

set elements are: [65, 10, 35, 30, 100, (this Collection)] list elements are: [20, SDJ, ajeet] set elements add to list: [20, SDJ, ajeet, 65, 10, 35, 30, 100, [65, 10, 35, 30, 100, (this Collection)]]

How to add elements through addAll(collection c) ) &Hashset(collection c) inside set:

  • In set interface it is also possible to add elements through addAll(collection c) method and Hashset(collection c) . The following example show

Example 4:

 
            
              package com.sdj.pack1;
              public class HashSetExmpl
              {
                 public static void main(String[] args)
                 {
                    HashSet set=new HashSet();
                    set.add("10");
                    set.add("30");
                    set.add("65");
                    set.add("35");
                    set.add("100");
                    set.add(set);
                    System.out.println(" set elements are:"+set);
                    Set set1=new HashSet();
                    set1.add(45);
                    set1.add("70");
                    set1.add("SDJ");
                    System.out.println("set1 elements are:"+set1);
                    set.addAll(set1);
                    System.out.println("Adding elements through addAll:"+set);
                 }
              } 
                   

Output:

set elements are:[65, 10, 35, 30, 100, (this Collection)] set1 elements are:[45, 70, SDJ] Adding elements to set through addAll:[45, 65, 10, 35, 30, 70, 100, SDJ, (this Collection)]

Example 5: Adding elements through HashSet(collection c).

 
            
              package com.sdj.pack1;
              import java.util.HashSet;
              import java.util.Set;
              public class SetExmpl
              {
                 public static void main(String[] args)
                 {
                    Set set=new HashSet();
                    set.add("10");
                    set.add("20");
                    set.add("SDJ");
                    set.add("65");
                    System.out.println(" set elements are:"+set);
                    Set set1=new HashSet(set);
                    System.out.println("Adding elements through Hashset():"+set);
                    set1.add("ram");
                    set1.add("rani");
                    set1.add("josh");
                    set.add("26");
                    set.addAll(set);
                    System.out.println("set1 elements are:"+set1);
                 }
              } 
                   

Output:

set elements:[65, 20, SDJ, 10] set1 elements through HashSet():[65, 20, 10, SDJ] set1 elements:[65, rani, 26, josh, 20, ram, 10, SDJ]

Reading Elements From Set Interface:

  • In set interface there is no any method with index based for reading data like get(index) in list interface.

  • We can iterate set interface by using the iterator object only.

  • Another way we can iterate is through enhanced for loop (or) for each for loop.Through iterator interface:

  • Inside set interface there is one method i.e iterator( ), it will return iterator type output and it is under java.util package

  • In iterator there are three methods to iterate.

    • hasNext()—explanation

    • next()--

    • remove()—

Example 6:

 
            
              package com.sdj.pack1;
              import java.util.HashSet;
              import java.util.Iterator;
              import java.util.Set;
              public class SetExample 
              {
                 public static void main(String[] args)
                 {
                    Set set1=new HashSet();
                    set1.add(10);
                    set1.add("SDJ");
                    set1.add("Life");
                    Set set2=new HashSet();
                    set2.add(10);
                    set2.add("WELCOME");
                    set2.add("ok");
                    set2.add(set1);
                    System.out.println("befor iterator elements are:"+set2);
                    Iterator it=set2.iterator();
                    while(it.hasNext())
                    {
                       Object elm=(Object)it.next();
                       System.out.println("afer iteration elements are:"+elm);
                    }
                    it.remove();
                 }
              } 
                   

Output:

Before iterate the set Elements: [[life, SDJ, 10], ok, welcome, 10] The iterate elements are: [life, 20, SDJ, 10] The iterate elements are: ok The iterate elements are: welcome The iterate elements are: 10

Syntax:

    for(Object obj : Set)

    {

    System.out.println(set);

    }

Example 7:

 
            
              package com.sdj.pack1;
              import java.util.HashSet;
              import java.util.Set;
              public class SetExample2
              {
                 public static void main(String[] args)
                 {
                    Set set1=new HashSet();
                    set1.add("10");
                    set1.add("SDJ");
                    set1.add("20");
                    set1.add("life");
                    Set set2=new HashSet();
                    set2.add(10);
                    set2.add("welcome");
                    set2.add(30);
                    set2.add(set1);
                    System.out.println("Before iterate elements:"+set2);
                    System.out.println("for each for loop");
                    for(Object obj:set2)
                    {
                       System.out.println("The elements are"+obj);
                    }
                 }
              } 
                   

Output:

Before iterate the set Elements:[[life, 20, SDJ, 10], 30, welcome, 10] For each For loop The Elements are: [life, 20, SDJ, 10] The Elements are: 30 The Elements are: welcome The Elements are: 10
    Note
    • List iterator won’t support for set and map collections, it is exclusively for the list interface only.How to remove elements from set interface:

Syntax:

    remove(Object obj);

    removeAll(collection c);

    retainAll(collection c);

Example 8:

 
            
              package com.sdj.pack1;
              import java.util.HashSet;
              import java.util.Set;
              public class Setexample3
              {
                 public static void main(String[] args)
                 {
                    Set set1=new HashSet();
                    set1.add(10);
                    set1.add("SDJ");
                    set1.add("20");
                    set1.add("life");
                    set1.add("java");
                    Set set2=new HashSet();
                    set2.add("java");
                    set2.add(40);
                    set2.add(50);
                    System.out.println(" before removing elements in set");
                    System.out.println(" set1 output"+set1);
                    System.out.println(" set2 output"+set2);
                    System.out.println("after removing elements in set");
                    System.out.println(set2.remove(40));
                    System.out.println("remove elements from set2"+set2);
                    set2.removeAll(set1);
                    System.out.println("elements after removeall():"+set2);
                    set2.retainAll(set1);
                    System.out.println("set2  element after retailall():"+set2);
                 }
              } 
                   

Output:

Before Removing elements in set set1 output is:[java, life, 20, SDJ, 10] set3 output is:[java, 40, 50] After removing Elements in set true set3 elements after remove:[java, 50] set3 elements by using removeAll: [50] set3 elements by using retainAll: [ ]

How to convert from Set to Arrays:

Syntax:

    Object objArray[ ]=setrefvariable.toArray( );

    String strarr[]=setrefvariable.toArray(new String[10] );

Example 9:

 
            
              package com.sdj.pack1;
              import java.util.HashSet;
              import java.util.Set;
              public class SetToArrayEx
              {
                 public static void main(String[] args)
                 {
                    Set set1=new HashSet();
                    set1.add("wecome");
                    set1.add(2);
                    set1.add("sdj");
                    set1.add("java");
                    System.out.println("elements in set1:"+set1);
                    Object objArray[]=set1.toArray();
                    System.out.println("converting set elements into array");
                    for(Object obj:objArray)
                    {
                       System.out.println(obj);
                    }
                 }
              } 
                   

Output:

Elements in set1:[java, 2, Welcome, SDJ] After converting set elements to Array java 2 Welcome SDJ

LinkedHashSet

  • By using Hashset we won’t get ordered output, if we want to get ordered output in set then we should go for LinkedHashset.

  • LinkedHashSet is same as HashSet class except order of output.

  • Linked list will give 100% guarantee incase of ordered output, means that in which order we add in the same order we gets the output that is the only difference compared to HashSet.

  • For example in List interface the methods are addAll(index , value), remove( ), removeAll( ), get(index).these methods works based on index values only.

Example 10:

 
            
              packagecom.sdj;
              public class LinkedHashSetExmpl
              {
                 public static void main(String[] args)
                 {
                    Set set1=new LinkedHashSet();
                    set1.add("Welcome");
                    set1.add(2);
                    set1.add("SDJ");
                    set1.add("To Learn");
                    set1.add("java");
                    System.out.println("The LinkedHashSet elements are:"+set1);
                 }
              } 
                   

Output:

The LinkedHashSet elements are:[Welcome, 2, SDJ, To Learn, java]