Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate Dictionary<T, U> in Java error

In C#

Dictionary<String, String> dictionary = new Dictionary<String, String>(); 

In Java, this errors with

Cannot instantiate the type Dictionary

What could be wrong?

In my code this follows with

dictionary.put("vZip", jsonUdeals.getString("vZip")); 

I know this sounds too trivial. But I am at a loss!
If Dictionary doesn't do it(which I strongly suspect by now), then which DataStructure to use.

like image 510
naveen Avatar asked Jan 08 '11 11:01

naveen


People also ask

How do you declare a Dictionary in Java?

A Java dictionary is an abstract class that stores key-value pairs. Given a key, its corresponding value can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs. The Dictionary object classes are implemented in java.

Can we use Dictionary in Java?

In Java, Dictionary is the list of key-value pairs. We can store, retrieve, remove, get, and put values in the dictionary by using the Java Dictionary class. In this section, we will discuss the Java Dictionary class that stores data in key-value pairs just like the Map interface.

How do you add a value to a Dictionary in Java?

The put() method of Dictionary is used to insert a mapping into the dictionary. This means a specific key along with the value can be mapped into a particular dictionary.


2 Answers

Dictionary is an abstract class in Java. It is also obsolete; you should use the Map interface instead; something like:

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

Note that HashMap<K,V> is a concrete class, but we're assigning it to a Map<K,V> reference, which is an interface. This is the recommended style in Java, because it allows you to switch HashMap for e.g. Hashtable at a later stage, without having to change everything.

like image 192
Oliver Charlesworth Avatar answered Oct 01 '22 21:10

Oliver Charlesworth


Use a HashMap as follows:

Map<String, String> dictionary = new HashMap<String, String>(); 
like image 33
vtx Avatar answered Oct 01 '22 19:10

vtx