如何在此程序中实现泛型,因此我不必在此行中转换为String:
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"
}
}
答案 0 :(得分:12)
您可以使用Hashtable
,但不鼓励使用Map
和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"
}
您可以将声明替换为:
Map<String, String> h = new Hashtable<String, String>();
一般来说,如果这是一个选项,你想在变量声明,参数声明和返回类型上使用接口,如果这是一个选项。
答案 1 :(得分:1)
Hashtable<String,String> h = new Hashtable<String,String>();
答案 2 :(得分:0)
你也可以使用ConcurrentHashMap,它类似于HashTable是线程安全的,但你也可以使用'通用'或参数化形式。
Map<String, String> myMap = new
ConcurrentHashMap<String,String>();