簡體   English   中英

Java泛型問題

[英]Java Generics Question

如何在此程序中實現泛型,因此不必在此行中強制轉換為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"
  }

}

您可以使用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"
}

您可以將聲明替換為:

Map<String, String> h = new Hashtable<String, String>();

通常,如果可以的話,您想使用接口來進行具體類的變量聲明,參數聲明和返回類型。

Hashtable<String,String> h = new Hashtable<String,String>();

您還可以使用ConcurrentHashMap ,就像HashTable是線程安全的一樣,但是您也可以使用“通用”或參數化形式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM