• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question reg. Adding elements to HashSet / TreeSet  RSS feed

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is about adding elements to an Collection.
I want to know whether the collection maintains the order the elements were added:
When you consider a TreeSet it is clear that the initial sequnce is not kept as the
TreeSet is a sorted set the elements are sorted after they are added.

Tree set sorts elements:


C:\Java\EigeneJavaProgramme>java ListOp1c
[This, a, is, test]

But why does the HashSet not keep the elements in the order they are added?
import java.util.*;
class ListOp1b {
public static void main(String args[]) {
Set l = new HashSet();
l.add("This");
l.add("test");
l.add("is");
l.add("a");
l.add("test");

System.out.println(l);
}
}
C:\Java\EigeneJavaProgramme>java ListOp1b
[This, is, test, a]
Why doesn’t it write: [This, is, a, test] ???

Thank you for your answers.
Thomas.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A HashSet is designed to find elements quickly, for those who don't care about order of elements but simply care whether an element is in the Set or not. To do this, HashSet organizes its elements according to their hashCode() - which generally has nothing to do with order of insertion.
Generally, the only Collections that maintain the order in which things were added are those that implement List. Also there is a Map called LinkedHashMap which maintains this sort of order. The documentation for these classes specifically says that they maintain insertion order. All other Collection and Map classes, however, do not.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!