• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

looking for an (keys/values) object that keep the elements order

 
Florent LOTHON
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried Hashtable, HashMap, ...
but the order of element added isn't kept :
This code :

Displays that :
Florent
Toto
Alexandre
Titi
instead the right order :
Florent
Toto
Titi
Alexandre
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Florent,
This doesn't belong in the advanced forum (as it is a pretty basic issue). That aside, Hashtable and HashMap are associative arrays. That is, they associate a key with its value. In order for a collection to keep things in the order that they are added, it will need to implement the List interface. I'd suggest looking at the J2SE API documentation to find collections that implement the java.util.List interface and pick one that suits your purposes. At that point you could add things to the end of the list, maintaining what you want here--the order things are added.
Unfortunately, you won't be able to have an associative array (like HashMap) that also keeps it in the order items are added--since they are somewhat diametrically opposed.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, JDK 1.4 added a LinkedHashMap class which behaves the way you need. Replace HashMap with LinkedHashMap and you should be all set (given that you use JDK 1.4, of course.)
I'm going to leave this here in "Advanced" since you already got a reply, and delete the one in "Beginner." Please post your questions to only one forum. Thanks.
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops. Thanks, Ernest.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic