LinkedHashSet

In this chapter you will learn:

  1. What is Java LinkedHashSet and how to use LinkedHashSet
  2. Copy all elements of LinkedHashSet to an Object Array

Use LinkedHashSet

The LinkedHashSet class extends HashSet and adds no members of its own. It is a generic class that has this declaration:

class LinkedHashSet<E>

E specifies the type of objects that the set will hold. Its constructors parallel those in HashSet.

LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted.

This allows insertion-order iteration over the set.

import java.util.LinkedHashSet;
//from  j  av a  2  s .  c o m
public class Main {

  public static void main(String[] args) {
    LinkedHashSet<Integer> lhashSet = new LinkedHashSet<Integer>();

    System.out.println("Size of LinkedHashSet : " + lhashSet.size());
    lhashSet.add(new Integer("1"));
    lhashSet.add(new Integer("2"));
    lhashSet.add(new Integer("3"));

    System.out.println(lhashSet.size());

    lhashSet.remove(new Integer("1"));

    System.out.println(lhashSet.size());
  }
}

The output:

Copy all elements of LinkedHashSet to an Object Array

import java.util.Arrays;
import java.util.LinkedHashSet;
//from j a  v a  2  s. c o m
public class Main {
  public static void main(String[] args) {

    LinkedHashSet linkedHashSet = new LinkedHashSet();

    linkedHashSet.add("1");
    linkedHashSet.add("2");
    linkedHashSet.add("java2s.com");

    Object[] objArray = linkedHashSet.toArray();
    System.out.println(Arrays.toString(objArray));
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What is Iterator and how to use Iterator
  2. Remove an element from Collection using Iterator
  3. Iterable and for each loop
Home » Java Tutorial » Set
HashSet
HashSet element adding
HashSet element removing and clearing
HashSet clone
HashSet iterator
HashSet properties
TreeSet
TreeSet elements adding
TreeSet subSet
NavigableSet
LinkedHashSet