Set Interface and HashSet Implementation

When we discuss about Set, one word must come to our mind is uniqueness i.e Set will not allow duplicates.

Set will allow null value, but it will allow only one null value

Set involves  three implementations.

  1. HashSet
  2. LinkedHashSet
  3. TreeSet

1. HashSet

When we talk about hashset we must remember some of the key points which is mentioned below.

  1. HashSet will not allow duplicates.
  2. Allow only one null value.
  3. It is an unsorted set.
  4. It is an unorderd set. So we cant predict the order of displaying while iterating the hashset.
  5. It is not threadsafe.
  6. It will not allow Random Access or retrieval.

Now we will see the implementation of Hashset.

CODE


package HashSet;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class HashSet_Integer_StringImplementation {
public static void main(String[] args) {
//String Implementation
System.out.println("String Implementation");
Set<String> stringSet = new HashSet();
stringSet.add("learn");
stringSet.add("from");
stringSet.add("examples");
stringSet.add("learn");
stringSet.add("from");
stringSet.add("shidhar");
System.out.println("String set values are :"+stringSet);
//Integer Implementation
System.out.println("Integer Implementation");
Set<Integer> integerSet = new HashSet<>();
integerSet.add(34);
integerSet.add(234);
integerSet.add(4);
integerSet.add(34);
System.out.println("Integer set values are :"+integerSet);
}
}

Output

String Implementation
String set values are :[shidhar, learn, from, examples]
Integer Implementation
Integer set values are :[34, 4, 234]

If we notice the output, we will see that hashset will not allow duplicates. Also in hashset we will not be having set() or get() methods because hashset will not allow Random access or retrieval.

We have seen hashset implementation for String and Integer Wrapper class, but we didn’t see how hashset will behave for User Defined Objects because hashset behave in different way for adding User Defined objects. In order to avoid duplicates for user defined objects we must have to override the equals and hashcode or else it will not avoid duplicates.

One Comment

  1. sonaksi singa October 10, 2014 Reply

Add a Comment

Your email address will not be published. Required fields are marked *