Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we not get the ordered sequence in HashSet

Tags:

java

hashset

I am using the HashSet for adding the elements and retrieving them, I know that I will not retrieve the data in sequence in which I added them, but I want to know the exact reason why Is it happeing?

import java.util.HashSet;
import java.util.Iterator;

 public class HS {
     public static void main(String args[]) {
         HashSet h=new HashSet();
         h.add("Mayank");
         h.add("Mayank");

         h.add("Vashist");
         h.add("Dinesh");

         h.add("Vashist");

         Iterator itr=h.iterator();
         while(itr.hasNext()) {
             System.out.println(itr.next());
         }
     }
 }
like image 954
Make Avatar asked Dec 02 '22 23:12

Make


1 Answers

This is just the contract for a Set in java, from the javadoc

Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee). So an implementation of Set isn't required to maintain any order in the values.

In order to return values in order the Set needs to maintain the order. This has costs for speed and space.

A LinkedHashSet maintains insertion order.

like image 54
Boris the Spider Avatar answered Dec 19 '22 05:12

Boris the Spider