adding elements in alphabetical order to a hashtable that deals with collisions using java
-
please help! i need to write java code that uses a hashtable to create a CD catalogue. ive used the artist name as a key and the cd as the value, the cd is a seprate class with instance variables: artistname, title and price. the problem im having is storing each new entry in alphabetical order. my current addcd method is public addCD( CD cd){ put( cd.getArtistname(), cd); } however this does not store it in alphabetical order in my hashtable. another problem im having is collions 1 artist has many cds, so how can i get the other cds stored by the same artist, ive read that hashtables deal automatically with collions by storing it in a linked list but my hashtable only returns the last cd entery that iv added. anny suggestions to the problem would be graetly appreciated
-
please help! i need to write java code that uses a hashtable to create a CD catalogue. ive used the artist name as a key and the cd as the value, the cd is a seprate class with instance variables: artistname, title and price. the problem im having is storing each new entry in alphabetical order. my current addcd method is public addCD( CD cd){ put( cd.getArtistname(), cd); } however this does not store it in alphabetical order in my hashtable. another problem im having is collions 1 artist has many cds, so how can i get the other cds stored by the same artist, ive read that hashtables deal automatically with collions by storing it in a linked list but my hashtable only returns the last cd entery that iv added. anny suggestions to the problem would be graetly appreciated
Hi, I am not a Java specialist, but I assume its collections are quite similar to the ones in .NET (they would be identical if you were refering to J# instead of Java). In .NET a hashtable holds a lot of key,value pairs; it applies a lot of tricks to handle large collections very fast (that is given a key, find the value). It does not store things in alphabetical order. It does include all necessary logic to avoid collisions (thats different keys producing the same hash; trying to enter two key,value pairs with same key results in an exception). If you want to traverse a collection alphabetically, you must have an ordered collection, that either sorts by itself (as in SortedList) or that supports an explicit Sort operation (as in ArrayList, and List). So one often ends up having two parallel collections, say a Hashtable for fast key->value translation, and a SortedList for listing the keys alphabetically. Hope this helps. :)
Luc Pattyn
try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }