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());
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With