简体   繁体   English

Java泛型问题

[英]Java Generics Question

How can I implement generics in this program so I do not have to cast to String in this line: 如何在此程序中实现泛型,因此不必在此行中强制转换为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"
  }

}

You could use a Hashtable but its use is discouraged in favour of Map and HashMap : 您可以使用Hashtable但不建议使用MapHashMap

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. 您还可以使用ConcurrentHashMap ,就像HashTable是线程安全的一样,但是您也可以使用“通用”或参数化形式。

 Map<String, String> myMap = new
     ConcurrentHashMap<String,String>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM