0

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

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for recommending use of interfaces for variable declarations, and return types where feasibile
Use Collections.synchronizedMap( new HashMap<...> () ) instead of hashtable.
1
Hashtable<String,String> h = new Hashtable<String,String>(); 

2 Comments

Hashtable is genericized as Hashtable<K, V>. java.sun.com/javase/6/docs/api/java/util/Hashtable.html
While I recommend using Map as the type this answer is technically correct so +1 to cancel out a somewhat overzealous downvote.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.