The Set collection

Another important collection present in Java is the Set collection/interface. HashSet, TreeSet, and LinkedHashSet are the three classes that implement the Set interface. The main difference between Set and List is that Set does not accept duplicate values. One more difference between the Set and List interfaces is that there is no guarantee that elements are stored in sequential order.

We will mainly be discussing HashSet in this section. We will take an example class and try to understand this concept. Create a class and name it hashSetexample for this section, and create an object within the class to use HashSet; it'll suggest you add the argument type, which is String in our case:

package coreJava;

import java.util.HashSet;

public class hashSetexample {

public static void main(String[] args) {

HashSet<String> hs= new HashSet<String>();

}
}

In your IDE when you type hs., it'll show you all the methods provided by HashSet:

Start by adding a few string instances of duplicate entries:

        HashSet<String hs= new HashSet<String>();
hs.add("USA");
hs.add("UK");
hs.add("INDIA");
hs.add("INDIA");
System.out.println(hs);

When you print this, the output will be as follows:

[USA, UK, INDIA]

We see that the duplicate entry for INDIA is rejected by HashSet and we only see one instance.

If we wish to remove any object, we can do so using the remove method, and to get the size of the list use the size method:

        System.out.println(hs.remove("UK"));
System.out.println(hs.isEmpty());
System.out.println(hs.size());

The isEmpty method tells us whether the list is empty—if it's empty, it'll return true, otherwise it returns false.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.30.232