Home Tutorial Java Core Java Collection : LinkedHashSet Example

 
 

Share on Google+Share on Google+
Java Collection : LinkedHashSet Example
Posted on: November 10, 2012 at 12:00 AM
Advertisement
This tutorial contains description of LinkedHashSet with example.

Java Collection : LinkedHashSet Example

This tutorial contains description of LinkedHashSet with example.

LinkedHashSet : LinkedHashSet class is defined in java.util package. It maintains doubly-Linked list and display the content in the same order as you inserted. It is an ordered version of HashSet. So when you need elements in ordered way insertion use LinkedHashSet in place of HashSet.

Example :

package collection;

import java.util.LinkedHashSet;

class LinkedHashSetExample{
public static void main(String[] args){

//Creating object of LinkedHashSet
LinkedHashSet<Integer> set=new LinkedHashSet<Integer>();

//Adding elements
set.add(100);
set.add(333);
set.add(400);
set.add(111);
System.out.println("Size of LinkedHashSet : "+set.size());
System.out.println("LinkedHashSet elemnts : "+set);

//Remove elements
set.remove(111);
System.out.println("After Deletion - ");
System.out.println("Size of LinkedHashSet : "+set.size());
System.out.println("LinkedHashSet elemnts : "+set);
}
}

Description : In this example we are implementing LinkedHashSet for integers. Create object of LinkedHashSet as -
LinkedHashSet<Integer> set=new LinkedHashSet<Integer>();
add(item)
method adds items to the set.
remove(item) method removes item from your list if the element exist in your set.

Output :

Size of LinkedHashSet : 4
LinkedHashSet elemnts : [100, 333, 400, 111]
After Deletion - 
Size of LinkedHashSet : 3
LinkedHashSet elemnts : [100, 333, 400]
Advertisement

Related Tags for Java Collection : LinkedHashSet Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 10, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com