SHAH NIRAV
SHAH NIRAV

Reputation: 35

Retrieval of data in HashSet

I want to know that in which manner, the data is retrieve in HashSet I have inserted data in different order and output data is in another order. Can someone please tell the logic behind this?

Code is like this :-

    class Test 
    { 
        public static void main(String[]args) 
        { 
            HashSet<String> h = new HashSet<String>(); 

            // Adding elements into HashSet using add() 
            h.add("India"); 
            h.add("Australia"); 
            h.add("South Africa"); 
            System.out.println(h); 
        }
}

Output:- [South Africa, Australia, India]

Upvotes: 1

Views: 481

Answers (5)

icSapper
icSapper

Reputation: 244

Use the LinkedHashSet if you want it to maintain the order of elements.

Upvotes: 0

Vankuisher
Vankuisher

Reputation: 76

As per the above, please see the Javadoc for HashSets - the order is not guaranteed. https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

Upvotes: 0

jwenting
jwenting

Reputation: 5663

As said, the ordering of elements in a HashSet is not guaranteed to be anything, nor to be constant over time.

This is due to the nature of the underlying data structure.

In your case, it looks like the Strings were stored in a LIFO queue, but another implementation of HashSet may well do things differently (and even this one might as more items get inserted, start to behave differently).

Upvotes: 0

Duega
Duega

Reputation: 73

HashSet works same as HashMap with Value. Moreover It internally uses HashMap With value constant Object called "PRESENT". By doing this HashSet guarantee uniqueness but not order It locate the set elements similarly as what Hashmap do.

You can see the implementation of HashSet on internet.

Upvotes: 0

mwe
mwe

Reputation: 3263

From Javadoc of HashSet

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

Upvotes: 3

Related Questions