Last Updated:

Set concept in Java

It is more convenient to store objects in a collection. There are many kinds of collections in Java, but they all extend the capabilities of ordinary arrays and have their own separate methods for manipulating data.

Set is one way to organize collections. In Java, sets are an interface. They inherit Set from the Collection interface (the main one for all sets). Sets have an unlimited length. This allows you to dynamically (during program execution) change the length of the set. For example, if the collection consists of 10 elements, you can freely add the 11th element or remove the 10th.

The Set interface, as well as the sortedSet, are inherited from the main interface of all Collections. Set and sortedSet extend the functionality of the Collection.

The Collection interface implements an abstract class for AbstractCollections. This class has many inheritors and an abstract derived class, AbstractSet, is defined for the sets. The Set, sortedSet, and AbstractSet interfaces and abstract classes implement classes for creating set objects. The following classes are defined for sets:

  1. HashSet. Objects in the set are indexed by keys — hash tags.
  2. TreeSet. Many sorted objects in the form of a tree.
  3. LinkedHashSet. Related objects in a set.

Generalized HashSet class

A HashSet is a hash table. Set objects of this class implement the functionality of the Set interface as well as the AbstractSet. A table is a set of objects where each object has a unique hash tag (key). A key allows you to assign a unique identifier to each object in the set. Only parent methods are implemented in the class and there are no individual methods.

The hashSet object implementation syntax has the following structure:

HashSet<T> variable = new HashSet<T>() — empty set

HashSet sets objects have the following methods from the Collection interface:

  • add(obj) — adds an object(obj) to the set, which can be either of the type specified in the generalization, or arbitrary if no generalization is specified. Returns true if there is no such object in the set; otherwise, false.
  • clear() — delete all objects of the set.
  • contains(Object obj) - Returns true if the set or collection contains an obj object.
  • isEmpty() - Checks whether the collection is empty, returns true or false.
  • remove(Object obj) — If the specified object is deleted successfully, it returns true.
  • removeAll (Collection<T> collection) - Remove all objects from the collection. Returns true if at least one object is deleted.
  • size() is the number of objects in the collection by type integer.
  • toArray() — translate the collection into an array and return it.

These methods are implemented by all collections. Methods are contained in the Collection interface. All abstract classes and objects of sets and other collections inherit these methods. In general, all collections differ from each other only in the way the data is stored, as well as in how it changes after adding or removing items.

Each collection also has a different method for indexing and identifying items. In other words, they work differently with memory, but their functionality is basically similar.

SortedSet interface

 

The SortedSet is designed to store items in ascending order. This set stores only unique elements. Elements are sorted by the number of memory occupied, the number of elements if it is an array or a string.

Sets of this interface have the following individual functions:

  • first() — returns the first element of the set;
  • last() — returns the last element of the set;
  • headSet(end) — returns all elements of the set up to the end element;
  • tailSet(start) returns all elements of the set, starting with the start element;
  • subSet(start, end) — returns all elements between start and end.

The syntax for creating a SortedSet object is:

SortedSet<string> variable = new SortedSet<string>(); for string objects, but also for any, depending on the <T>.

Example:

SortedSet<integer> set_int = new SortedSet<integer>();
set_int.add(5);
set_int.add(2);
set_int.size(); 2
set_int.remove(2);
set_int.size(); 1

Generic TreeSet class

The data structure in this set is represented as a tree. Here, objects are stored in a sorted sequence in ascending order—by memory size or item seniority. This class supports all standard Collection methods.

Example:

TreeSet<String> vegetables = new TreeSet<String>();

add a few vegetable names to the
set, vegetables.add ("potatoes");
vegetables.add(«tomato»);
vegetables.add(«cabbage»);
vegetables.add(«carrot»);

System.out.printf(«Here is», states.size(), «groups of vegetables»);

remove one of the elements of
vegetables.remove ("carrot");
vegetables.size(); 3
// If we output all the elements of the tree through a loop, we get a sorted set of elements alphabetically: cabbage->carrot->potato->tomato.

In general, TreeSet implements interfaces such as NavigableSet and SortedSet, so many of this class get all the functionality of these interfaces, plus Collection.

NavigableSet interface

 

This interface is an extension of SortedSet. Sets of this interface have the following individual methods:

  • ceiling(obj) — looks for an element that is smaller in structure than obj and returns it;
  • floor(obj) is the same as the previous one, only the element is larger and larger than obj;
  • higher(obj) — analogue of ceiling;
  • lower(obj) — analogue of floor;
  • pollFirst() — return the first element and remove it from the set;
  • pollLast() - similar to the previous one, only the last element is deleted;
  • descendingSet() — the set of NavigableSet is returned, only the elements are arranged in reverse order;

Example:

NavigableSet<String> fruits = new NavigableSet<String>();

add a few vegetable names to the
set fruits.add ("banana");
fruits.add(«pineaple»);
fruits.add(«apple»);
fruits.add(«orange»);

System.out.printf(«Some of», states.size(), «groups of fruits»);

remove one of the fruits.remove elements
("apple");
fruits.size(); 3
for(int x : fruits ){system.out.print(x)} // banana, orange, pineaple

fruits.last(); orange

NavigableSet<String> back_fruits = fruits.descendingSet();
for(int x : back_fruits ){system.out.print(x)} // pineaple, orange, banana

Iterator method for sets

This method belongs to the Collection interface. It returns an Iterrator object. It has its own individual methods, such as next(), hasNext(), nextIndex().

Example:

TreeSet<String> movies = new TreeSet<String>();
movies.add(«Commando»);
movies.add(«Harry Potter»);
movies.add(«Spiderman»);
movies.add(«Batman»);

Iterator<String> SetIterator = movies.iterator();
while(iter.hasNext()){ // So far the iterator has the following element

System.out.println(iter.next()); Commando, Harry Potter, Spiderman, Batman

The iterator is useful if the set or collection will often have to be cycled through. Special iterator techniques make it easier to work with a collection.

Total

Sets are a convenient way to store unique objects. Sets have no size limitations. Initialization does not require specifying a fixed memory size. Lists can be called "rubber" - you can dynamically add elements to infinity. If we talk about all types of lists, they only distribute items in memory differently:

  • ordered storage,
  • Disordered
  • elements are generalized or arbitrary.

However, it is worth noting that all sets, and the collection as a whole, use the same methods. Sets and other types of collections have a structure distinguishable from arrays. Sometimes this becomes necessary in certain conditions. But for a while, collections only provide a convenient way to organize and store individual objects.