It's not a secret anymore!
The moose likes Beginning Java and the fly likes Collections problem - reference by index and key? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections problem - reference by index and key?" Watch "Collections problem - reference by index and key?" New topic

Collections problem - reference by index and key?

Bill Pearce
Ranch Hand

Joined: Sep 19, 2000
Posts: 53
Hi all,
I am trying to implement a UserList class which should provide the caller with the following functions (among others):
Get a User by userId.
Get a User by index in the list.
Allow for sorting based on userId or name and move elements up and down in the list(using Comparator or something similar).
I am having trouble picking the best Class to act as the underlying Collection. Hashtable works for the first requirement, but not really well for the second and third (I tried using htable.values().toArray()[i] for the second requirement, but it seems a little awkward).
Vector handles the second two great, but I can't figure how best to reference by userId without looping through the whole list looking for the one I want.
I thought about maintaining a Vector and a separate index of userId's, but this seems risky.

Any suggestions?

William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Well I can't say that I have used one yet, but how about TreeMap? It would should solve the sorted issue.

Please ignore post, I have no idea what I am talking about.
Bill Pearce
Ranch Hand

Joined: Sep 19, 2000
Posts: 53
Hope no one minds me taking another shot at this...
The TreeMap gets me close, but not all the way there. My requirements are these:
Reference elements by index (position in list, as with Vector).
Reference elements by key (as with Hashtable).
Move elements up or down in the list (as is possible creating your own Comparator and using Collections.sort(List, Comp)).
Sort list based on field of the elements in the list (like or, again possible with Comparator).
So it looks like I need to combine a couple of features of Map with a couple from List. I need an ordered list of elements that will let me reference elements by a key and allow me to handle the sorting of the list. Is this possible by subclassing one of the existing Java classes? If so, does anyone have a suggestion as to which?

Any help appreciated.
I agree. Here's the link:
subject: Collections problem - reference by index and key?
It's not a secret anymore!