How can I implement generics in this program so I do not have to cast to String in this line:
String d = (String) h.get ("Dave");
import java开发者_开发百科.util.*;
public class TestHashTable {
public static void main (String[] argv)
{
Hashtable h = new Hashtable ();
// Insert a string and a key.
h.put ("Ali", "Anorexic Ali");
h.put ("Bill", "Bulimic Bill");
h.put ("Chen", "Cadaverous Chen");
h.put ("Dave", "Dyspeptic Dave");
String d = (String) h.get ("Dave");
System.out.println (d); // Prints "Dyspeptic Dave"
}
}
You could use a Hashtable
but its use is discouraged in favour of Map
and HashMap
:
public static void main (String[] argv) {
Map<String, String> h = new HashMap<String, String>();
// Insert a string and a key.
h.put("Ali", "Anorexic Ali");
h.put("Bill", "Bulimic Bill");
h.put("Chen", "Cadaverous Chen");
h.put("Dave", "Dyspeptic Dave");
String d = h.get("Dave");
System.out.println (d); // Prints "Dyspeptic Dave"
}
You could replace the declaration with:
Map<String, String> h = new Hashtable<String, String>();
In general you want to use interfaces for your variable declarations, parameter declarations and return types over concrete classes if that's an option.
Hashtable<String,String> h = new Hashtable<String,String>();
You could also use a ConcurrentHashMap, which like HashTable is Thread safe, but you can also use the 'generic' or parameterized form.
Map<String, String> myMap = new
ConcurrentHashMap<String,String>();
精彩评论