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.
Post by:William Barnes
Well I can't say that I have used one yet, but how about TreeMap? It would should solve the sorted issue.
Post by:Bill Pearce
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 user.name or user.id, 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. Bill
Attractive, successful people love this tiny ad:
Programmatically Create PDF Using Free Spire.PDF with Java