Set Interface in java

The Set

A set is not implicitly ordered.

A set contains no duplicates.

A set may contain a single null element.

Set Methods

The Set Interface defines the basic method add, remove, and clear, to maintain the item in the set.

We can also check if a specific item is in the set using the contains methods.

Interestingly enough, there is no way to retrieve an item from a set.

You can check if something exists, using contains and you can iterate over all the elements in the set, but attempting to get the 10th element.

for example from a set is not possible, with a single method.

How HashSet Works Internally

HashSet uses a hash table for storing the elements. It uses a hashmap to store elements as keys, with dummy values. When you add an element to a HashSet the element is hashed using the hashCode() method, and the resulting hash code is used to determine the bucket location in the hash table where the element will be stored.

If another element is hashes to the same bucket (collision), HashSet handles it by a linked list or a binary tree (depending on java version) to store multiple elements with the same hash code in the same bucket.

    public static void main(String[] args) {

        String aText = "Hello";
        String bText = "Hello";
        String cText = String.join("l", "He", "lo");
        String dText = "He".concat("llo");
        String eText = "hello";

        //creating a list of hellos
        List<String> hellos = Arrays.asList(aText, bText, cText, dText, eText);

        //iterating through all the element to get the hash code of particular element
        hellos.forEach(s -> System.out.println(s + ": " + s.hashCode()));
//        output
//        Hello: 69609650
//        Hello: 69609650
//        Hello: 69609650
//        Hello: 69609650
//        hello: 99162322
        //creating a set of hellos
        Set<String> mySet = new HashSet<>(hellos);
        System.out.println("mySet " + mySet);//mySet [Hello, hello]
        System.out.println("mySet " + mySet.size());//mySet 2

        //lopping through the set
        for (String setValue : mySet) {
            System.out.print(setValue + ": ");

            //loop for list of hellos
            for (int i = 0; i < hellos.size(); i++) {
                //checking if elements are equal
                if (setValue == hellos.get(i)) {
                    System.out.print(i + ", ");
//        Hello: 0, 1,
//        hello: 4,


Author: Susheel kumar

Leave a Reply

Your email address will not be published. Required fields are marked *