package datastrcutures;
import java.util.*;
public class java_hashtable {
public static void ratingof开发者_如何学JAVAcity() {
Hashtable CityRating = new Hashtable();
CityRating.put("New York", "8");
CityRating.put("Sandton", "9");
}
}
I think you have a typo there, your object type has to be Hashtable
instead of Hasttable
And you should use Java Generics
Instantiate your hash table object like this:
Hashtable<String, String> cityRating = new Hashtable<String, String>();
And as Java naming convention I would suggest having your object name start with a lower case letter.
The question Is this correct usage of a hashtable
is very subjective.
A Map
is used to storing sets of keys and values like in your example.
However - things you should consider in your design:
- Do I need my map to be Thread-Safe? if not, use a HashMap
- Can you have the same rating for two cities? If not, maybe an array would be better?
- If the answer to the above question is "yes" - do you need to get all the cities with the same rating? at which case you might need to come up with another data structure, or simply maintain two maps (one of City -> Rating and one of Rating -> City)
- Is the rating OK with being a
String
- wouldn't you prefer anInteger
so you can compare them?
Also, a few notes not related to the "design" of this question:
- Prefer declaring the interface of the Collection you use instead of the implementation - it makes code changes easier and makes your API more robust.
- Use generics - it makes code type safe and easier to read. e.g.
Map<String, Integer> cityRatings = new Hashtable<String, Integer>();
import java.util.*;
public class java_hashtable {
public static void ratingofcity() {
Hashtable<String, String> cityRating = new Hashtable<String, String>();
CityRating.put("New York", "8");
CityRating.put("Sandton", "9");
}
}
Hashtable is declared in a wrong way. The changes which I made must work now.
精彩评论