Java Reference
In-Depth Information
Using Different Types of Collections
In this section, I will discuss different types of collections and their variants, such as sets, lists, queues, maps, etc.
Working with Sets
A set is mathematical concept that represents a collection of unique objects. In mathematics, the ordering of elements
in a set is irrelevant. The Collections Framework offers three types of sets:
Mathematical set
Sorted set
Navigable set
The following sections cover all types of sets in detail.
Mathematical Set
The Set interface models a set in mathematics. In mathematics, a set is a collection of unique elements. That is, a set
cannot contain duplicate elements. Java allows at most one null element in a Set because one null element is still
distinguishable from all other non-null elements and thus, it is unique. Further, the ordering of the elements in a
mathematical set is not important. Java follows the same rule; it does not guarantee the ordering of the elements in a
Set . You can add elements to a Set in one order, and when you retrieve them, they may be supplied back in a different
order. The only guarantee is that when looping through all elements of a Set, you get each element in the Set once.
The Collections Framework provides the HashSet class as an implementation for the Set interface. Listing 12-5
demonstrates how to create a Set and add elements to it. Note that you can attempt to add duplicate elements to a
Set and they are ignored silently. Two elements in a Set are considered equal if comparing them using the equals()
method returns true.
Listing 12-5. Using the Set Interface with HashSet as Its Implementation Class
// SetTest.java
package com.jdojo.collections;
import java.util.HashSet;
import java.util.Set;
public class SetTest {
public static void main(String[] args) {
// Create a set
Set<String> s1 = new HashSet<>();
// Add a few elements
s1.add("John");
s1.add("Donna");
s1.add("Ken");
s1.add("Ken"); // Duplicate!!! No effect
// Create another set by copying s1
Set<String> s2 = new HashSet<>(s1);
 
Search WWH ::




Custom Search