LinkedHashSet
In this chapter you will learn:
- What is Java LinkedHashSet and how to use LinkedHashSet
- 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;
/* j a v 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 jav 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:
- What is Iterator and how to use Iterator
- Remove an element from Collection using Iterator
- Iterable and for each loop
Home » Java Tutorial » Collections