Set interface takes you to learn advanced features of Java language

【Objective of this program】

This section introduces the inheritance relationship and characteristics of the Set interface, and introduces the use of two commonly used subclasses: HashSet and TreeSet.

Set interface
The biggest feature of the Set collection is that it does not allow to save duplicate elements, which is also a Collection subinterface.

Before JDK1.9, there is no difference between the definition of Set collection and Collection collection. Set continues to use the methods provided in the Collection interface for operations. However, after JDK1.9, Set collection also expands some static methods like List collection. Set A collection is defined as follows:

public interface Set extends Collection

It should be noted that the Set collection does not expand many new methods like the List collection, so the get() method provided in the List collection cannot be used, that is to say, the specified index data cannot be obtained. The inheritance relationship of the Set interface is as follows.

Since JDK1.9, the Set collection also provides a static method of of() similar to the List collection. Next, use this method to verify the characteristics of the Set collection.

Example: Verifying Set collection characteristics

When using the new method of(), if duplicate elements are found in the collection, an exception will be thrown directly. This is consistent with the fact that the traditional Set collection does not save duplicate elements, but it throws an exception.

The regular use form of the Set collection must rely on subclasses for instantiation, so there are two commonly used subclasses in the Set interface: HashSet and TreeSet.

HashSet subclass

HashSet is the most used subclass of the Set interface. Its biggest feature is that the stored data is out of order, and the inheritance relationship of the HashSet subclass is as follows.

Through the execution results, you can find the operating characteristics of HashSet: it is not allowed to save duplicate elements (defined by the Set interface), and another feature is that the data stored in HashSet is out of order.

TreeSet subclass

Another sub-interface of the Set interface is TreeSet. The biggest difference from HashSet is that the data stored in the TreeSet collection is ordered. First, let's observe the definition of the TreeSet class.

When using TreeSet to save data, all data will be automatically sorted according to the ascending order of data.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us