kamlesh
kamlesh

Reputation: 29

Hashtable raw type

I'm getting this warning here is code:

Hashtable nu=new Hashtable();
Hashtable ns=new Hashtable();
nu.put(new String("postmaster"),new String("admin"));
ns.put(new String("SMTP"),new String(""));
ns.put(new String("POP3"),new String(""));
ns.put(new String("EMAIL"),new String(""));
ns.put(new String("USER"),new String(""));
ns.put(new String("PASS"),new String(""));

warning: [unchecked] unchecked call to put(K,V) as a me mber of the raw type Hashtable

Upvotes: 2

Views: 6110

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213311

Hashtable is a generic type. You should use the corresponding parameterized type by passing the type arguments, while using it. Just using the class name Hashtable is raw type, and is discouraged, except in some places, where you have to use them.

So, you would instantiate the object as:

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

However, you should also avoid using a Hashtable. The reason being, every operation of Hashtable is synchronized, which you really don't need. That unnecessarily makes the execution slow. Better to use a HashMap instead. You can use it like this:

Map<String, String> map = new HashMap<String, String>();
Map<String, String> map2 = new HashMap<>();   // Valid from Java 7 onwards

Apart from that, you don't need to create a new String object using new String(...), while adding them to the map. Just use string literals, so as t avoid unnecessary object creation:

nu.put("postmaster", "admin");  // Will work fine

Related:

Upvotes: 4

Dan D.
Dan D.

Reputation: 32391

If you are going to use generic types when declaring the Hashtable, the warning will go away:

Hashtable<String, String>

Or even better, code to an interface:

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

And maybe you can find a better implementation for Map than Hashtable, for instance HashMap:

Map<String, String> ns = new HashMap<String, String>();

Upvotes: 0

micha
micha

Reputation: 49592

Hashtable is a generic class with two generic type parameters.

Try:

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

It is not required to specify the generic parameters (String and String in this example). However, if you don't specify them you get the warning you mentioned.

See Hashtable javadoc and the section about generics in the oracle java documentation for more details.

Upvotes: 0

Related Questions