Basics of Set

suggest change

What is a Set?

A set is a data structure which contains a set of elements with an important property that no two elements in the set are equal.

Types of Set:

  1. HashSet: A set backed by a hash table (actually a HashMap instance)
  2. LinkedHashSet: a set backed by a hash table and a linked list, with predictable iteration order
  3. TreeSet: A NavigableSet implementation based on a TreeMap.

Creating a set

Set<Integer> set = new HashSet<Integer>(); // Creates an empty Set of Integers

Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); // an empty set with predictable iteration order

Adding elements to a Set

Elements can be added to a set using the add() method

set.add(12); //  - Adds element 12 to the set
set.add(13); //  - Adds element 13 to the set

Our set after executing this method:

set = [12, 13]

HashSet does not promise this order.

Delete all the elements of a Set

set.clear();  //Removes all objects from the collection.

After this set will be:

set = []

Check whether an element is part of the Set

Existence of an element in the set can be checked using the contains() method

set.contains(0);  //Returns true if a specified object is an element within the set.

Returns false. contains returns a boolean; it does not print False.

Check whether a Set is empty

isEmpty() method can be used to check whether a Set is empty.

set.isEmpty();  //Returns true if the set has no elements

Returns true after clear(), because that call removed every element. Earlier, after add, it would return false.

Remove an element from the Set

set.remove(0); // removes 0 if it is present; a set has no duplicate "first" occurrence

Check the Size of the Set

set.size(); //Returns the number of elements in the collection

Output: 0

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents