set

First, solve the problem. Then, write the code. John Johnson

LinkedHashSet

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-24 11:30:14

0 Comments


Definition

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements and maintains insertion order. It provides constant-time performance for the basic operations.

Character

LinkedHashSet does not allow to store duplicates.
It is not thread-safe and throw ConcurrentModificationException when multiple threads access the linked hash set object.
LinkedHashSet maintains insertion order when inserting the element.

source Code

								
package com.careerdrill.collections.set;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetUse {

	public static void main(String[] args) {
		
		int []array={34,67,45,34,27,98,56};
		System.out.print("Array of elements before insert the data to LinkedHashSet: "+ Arrays.toString(array));
		
		Set< Integer > hs = new LinkedHashSet< Integer >();
	     

		for(Integer i : array)
			hs.add(i);

		   Iterator< Integer > iterator = hs.iterator(); 
		      
		   System.out.print("\nLinkedHashSet elements which maintain insertion order: ");
		   while (iterator.hasNext()){
		   System.out.print(iterator.next() + " ");  
		   }
		   
	}

}
						

Output

    					 
Array of elements before insert the data to LinkedHashSet: [34, 67, 45, 34, 27, 98, 56]
LinkedHashSet elements which maintain insertion order: 34 67 45 27 98 56
    					 
					    

Comparison

HashSet LinkedHashSet TreeSet
HashSet does not maintain insertion order LinkedHashSet maintains insertion order TreeSet provides natural sorting
HashSet allows null LinkedHashSet allows null TreeSet does not allow null
O(n) O(1) O(logn)
Implemented using hash table Implemented using doubly linked list Implemented using red block tree
Not allowed to store duplicates Not allowed to store duplicates Not allowed to store duplicates
Compare HashSet uses equals() and hashCode() methods Compare HashSet uses equals() and hashCode() methods Comparable or comparator interface implementation

When to use

When you need to maintain the insertion order in addition to unique elements, you can use LinkedHashmap.

0 Comments



Please login to add comments.