Home  >  Core Java

Example of LinkedHashSet in Java

By Arvind Rai, June 09, 2013
java.util.LinkedHashSet has been introduced in java since JDK 1.4. java.util.LinkedHashSet has following features.

1. No duplicate element can be added.
2. Maintains insertion order.

The class which object is being added in the LinkedHashSet must override equals and hashCode to identify duplicate element. To maintain insertion order LinkedHashSet uses doubly-linked list.

3. By default LinkedHashSet is not synchronized but can be synchronized as
Set s = Collections.synchronizedSet(new LinkedHashSet());
 


LinkedHashSetDemo.java
package com.concretepage.util;
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetDemo {
    public static void main(String[] args) {
        Set<Bean> set = new LinkedHashSet<Bean>();
        Bean b1 = new Bean("A");
        Bean b2 = new Bean("B");
        Bean b3 = new Bean("C");
        set.add(b1);
        set.add(b2);
        set.add(b3);
        for(Bean b : set){
            System.out.print(b.name+" ");
        }
        System.out.println("\nsize before duplicate element:"+set.size());
        //add duplicate in LinkedHashSet
        Bean b4 = new Bean("C");
        set.add(b4);
        //no effect on size of LinkedHashSet
        System.out.println("size after duplicate element:"+set.size());
    }
}
class Bean {
    public String name;
    public Bean(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        return name.equals(((Bean)o).name);
    }
    @Override
    public int hashCode() {
        int hash = 13;
        hash = (31 * hash) + (null == name ? 0 : name.hashCode());
        return hash;
    }
}


Output
A B C 
size before duplicate element:3
size after duplicate element:3
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us