Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question reg. Adding elements to HashSet / TreeSet

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Talk sense to a fool and he calls you foolish. -Euripides A foolish tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic