Organizational Research By

Surprising Reserch Topic

LinkedHashSet Class in Java with Example

Earlier we have shared tutorials on HashSet and TreeSet. LinkedHashSet is also an implementation of Set interface, it is similar to the HashSet and TreeSet except the below mentioned differences:

HashSet doesn’t maintain any kind of order of its elements.
TreeSet sorts the elements in ascending order.
LinkedHashSet maintains the insertion order. Elements gets sorted in the same sequence in which they have been added to the Set.
Example of LinkedHashSet:

import java.util.LinkedHashSet;
public class LinkedHashSetExample {
     public static void main(String args[]) {
         // LinkedHashSet of String Type
         LinkedHashSet lhset = new LinkedHashSet();

         // Adding elements to the LinkedHashSet

         // LinkedHashSet of Integer Type
         LinkedHashSet lhset2 = new LinkedHashSet();

         // Adding elements

[Z, PQ, N, O, KK, FGH]
[99, 7, 0, 67, 89, 66]
Observe the output: Both types of LinkedHashSet have preserved the insertion order.

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes

Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.