package datastrcutures;
import java.util.*;
public class java_hashtable {
public static void ratingofcity() {
Hashtable CityRating = new Hashtable();
CityRating.put("New York", "8");
CityRating.put("Sandton", "9");
}
}
Asked
Active
Viewed 202 times
0

Aaron
- 11,239
- 18
- 58
- 73
-
And what you actually want to do with this code? Is the value ("8", "9") going to be unique? – Paweł Dyda Apr 23 '11 at 16:57
-
Out of convention variable name should be cityRating and not CityRating. – Paweł Dyda Apr 23 '11 at 16:58
-
And you might think about renaming the package to `datastructures`. – Paŭlo Ebermann Apr 23 '11 at 20:29
3 Answers
2
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.

anubhava
- 761,203
- 64
- 569
- 643
-
1And have a look at HashMap. See http://stackoverflow.com/questions/40471/java-hashmap-vs-hashtable – Axel Apr 23 '11 at 16:49
2
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>();

RonK
- 9,472
- 8
- 51
- 87
0
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.

Rasazna Kls
- 1
- 1