如何在此程序中实现泛型,因此我不必在此行中转换为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"
}
}
Run Code Online (Sandbox Code Playgroud)
cle*_*tus 12
你可以使用a 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"
}
Run Code Online (Sandbox Code Playgroud)
您可以用以下内容替换声明:
Map<String, String> h = new Hashtable<String, String>();
Run Code Online (Sandbox Code Playgroud)
通常,如果这是一个选项,您希望在具体类上使用接口作为变量声明,参数声明和返回类型.