tags:

views:

113

answers:

3

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"
  }

}
+1  A: 
Hashtable<String,String> h = new Hashtable<String,String>();
Software Monkey
Not sure this'll work--HashTable doesn't use Generics.
Tom
Hashtable is genericized as `Hashtable<K, V>`.http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html
polygenelubricants
My mistake--I was looking at the wrong docs.
Tom
While I recommend using `Map` as the type this answer is technically correct so +1 to cancel out a somewhat overzealous downvote.
cletus
+12  A: 

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.

cletus
+1 for recommending use of interfaces for variable declarations, and return types where feasibile
Everyone
Use `Collections.synchronizedMap( new HashMap<...> () )` instead of hashtable.
KitsuneYMG
A: 

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