LinkedHashSet

java.util.LinkedHashSet Example

In this post, we are going to discuss about the class java.util.LinkedHashSet and give you an idea of how you can use it on your own code when you want to manage collections of objects.

Applications often must manage collections of objects. Although you can use arrays for this purpose, they are not always a good choice. For example, arrays have fixed sizes, making it tricky to determine an optimal size when you need to store a variable number of objects. Also, arrays can be indexed by integers only, which make them unsuitable for mapping arbitrary objects to other objects. Java’s standard class library provides the Collections Framework and legacy APIs to manage collections on behalf of applications.

1. LinkedHashSet Class

LinkedHashSet is a subclass of HashSet that uses a linked list to store its elements. As a result, LinkedHashSet’s iterator returns elements in the order in which they were inserted. The HashSet class provides a set implementation that is backed by a hashtable data structure (implemented as a HashMap which provides a quick way to determine if an element has already been stored in this structure). HashSet permits the null reference to be stored in its instances.

2. Executing some code

Suppose you want to add instances of your classes to a hashset. Your classes must override equals() and hashCode(); otherwise, duplicate class instances can be stored in the hashset.

Planet.java

package com.javacodegeeks.examples.linkedhashset.beans;

public class Planet {
    private String name;
    private int    positionFromTheSun;

    public Planet() {}

    public Planet(String name, int positionFromTheSun) {
        this.name               = name;
        this.positionFromTheSun = positionFromTheSun;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPositionFromTheSun() {
        return positionFromTheSun;
    }

    public void setPositionFromTheSun(int positionFromTheSun) {
        this.positionFromTheSun = positionFromTheSun;
    }

    @Override
    public String toString() {
        return "Planet [name = " + name + ", positionFromTheSun = " + positionFromTheSun + "]";
    }

    @Override
    public int hashCode() {
        final int prime  = 31;
        int       result = 1;

        result = prime * result + ((name == null)
                                   ? 0
                                   : name.hashCode());
        result = prime * result + positionFromTheSun;

        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        Planet other = (Planet) obj;

        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }

        if (positionFromTheSun != other.positionFromTheSun) {
            return false;
        }

        return true;
    }
}

App.java

package com.javacodegeeks.examples.linkedhashset;

//~--- non-JDK imports --------------------------------------------------------

import com.javacodegeeks.examples.linkedhashset.beans.Planet;

//~--- JDK imports ------------------------------------------------------------

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

public class App {
    public static void main(String[] args) {
        Set<Planetgt; planets = new LinkedHashSet<>();

        planets.add(new Planet("Mercurio", 1));
        planets.add(new Planet("Saturno", 6));

        // Try to add the same object twice
        planets.add(new Planet("Mercurio", 1));
        planets.add(new Planet("Venus", 2));
        planets.add(new Planet("Tierra", 3));
        planets.add(new Planet("Marte", 4));
        planets.add(new Planet("Jupiter", 5));
        planets.add(new Planet("Urano", 7));

        // Try to add the same object twice
        planets.add(new Planet("Marte", 4));
        planets.add(new Planet("Pluton", 9));

        // Try to add the same object twice
        planets.add(new Planet("Urano", 7));
        planets.add(new Planet("Neptuno", 8));
        System.out.println("Number of planets: " + planets.size());

        if (!planets.isEmpty()) {
            Iterator it = planets.iterator();

            while (it.hasNext()) {
                System.out.println(it.next());
            }
        }

        planets.remove(new Planet("Pluton", 9));
        planets.add(null);
        System.out.println("");

        if (!planets.isEmpty()) {
            Iterator it = planets.iterator();

            while (it.hasNext()) {
                System.out.println(it.next());
            }
        }
    }
}

Let’s explain the methods used in the previous code

  • public boolean add(E e) – Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
  • public int size() – Returns the number of elements in this set (its cardinality).
  • public boolean isEmpty() – Returns true if this set contains no elements.
  • public Iterator<E> iterator() – Returns an iterator over the elements in this set.
  • public boolean remove(Object o) – Removes the specified element from this set if it is present. More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if this set contains such an element.

The output of the command

com.javacodegeeks.examples.linkedhashset.App

should be similar to:

Number of planets: 9
Planet [name = Mercurio, positionFromTheSun = 1]
Planet [name = Saturno, positionFromTheSun = 6]
Planet [name = Venus, positionFromTheSun = 2]
Planet [name = Tierra, positionFromTheSun = 3]
Planet [name = Marte, positionFromTheSun = 4]
Planet [name = Jupiter, positionFromTheSun = 5]
Planet [name = Urano, positionFromTheSun = 7]
Planet [name = Pluton, positionFromTheSun = 9]
Planet [name = Neptuno, positionFromTheSun = 8]

Planet [name = Mercurio, positionFromTheSun = 1]
Planet [name = Saturno, positionFromTheSun = 6]
Planet [name = Venus, positionFromTheSun = 2]
Planet [name = Tierra, positionFromTheSun = 3]
Planet [name = Marte, positionFromTheSun = 4]
Planet [name = Jupiter, positionFromTheSun = 5]
Planet [name = Urano, positionFromTheSun = 7]
Planet [name = Neptuno, positionFromTheSun = 8]
null

3. Download the Eclipse project of this tutorial:

This was an example of how to set use the LinkedHashSet Class.

Download
You can download the full source code of this example here: linkedhashset.zip

Armando Flores

Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button