开发者

Java Generics Question

开发者 https://www.devze.com 2022-12-21 11:35 出处:网络
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\");

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>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号