Java - Collection Framework Set

Introduction

Set interface models a set in mathematics, which is a collection of unique elements.

A set cannot contain duplicate elements.

Java allows at most one null element in a Set.

Set does not guarantee the ordering of the elements.

HashSet class is an implementation for the Set interface.

The following code creates a Set and adds elements to it.

If you attempt to add duplicate elements to a Set and they are ignored silently.

Two elements in a Set are considered equal if the equals() method returns true.

Demo

import java.util.HashSet;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    // Create a set
    Set<String> s1 = new HashSet<>();

    // Add a few elements
    s1.add("XML");
    s1.add("Json");
    s1.add("Java");
    s1.add("Java"); // Duplicate!!! No effect

    // Create another set by copying s1
    Set<String> s2 = new HashSet<>(s1);
    // Add a few more elements
    s2.add("Python");
    s2.add("Ruby");
    s2.add(null); // one null is fine
    s2.add(null); // Duplicate!!! No effect

    // Print the sets
    System.out.println("s1: " + s1);
    System.out.println("s1.size(): " + s1.size());

    System.out.println("s2: " + s2);
    System.out.println("s2.size(): " + s2.size());
  }/*from ww  w  . j  a  v a2s . c o m*/
}

Result

Related Topics

Exercise