Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Hashtables in Java?

Tags:

java

In C# you can initialize Hashtables (and many other types of objects) using code like this -

Hashtable table = new Hashtable {{1, 1}, {2, 2}};

Is there anything like this in Java or do you have to just declare the Hashtable first and then manually put items in it one by one?

like image 434
Jim_CS Avatar asked Mar 08 '12 21:03

Jim_CS


People also ask

What are Hashtables in Java?

A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. Java Hashtable class contains unique elements.

How do you add to a Hashtable in Java?

put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.

How is Hashtable synchronized in Java?

Hashtable methods are synchronized, but that only provides method-level protection against race conditions. (So a Hashtable —unlike a HashMap —will not become internally corrupted if multiple threads are concurrently trying to modify the data.) It is only in this sense that Hashtable is thread-safe.


1 Answers

This is answered elsewhere but you can use an anonymous subclass:

new HashMap<Integer, Integer>() {{ put(1, 1); put(2, 2); }};

Lot's of boiler plate, but still a one-liner :). This will, unfortunately, also complain about the missing serialVersionUID constant which you can either add or ignore the warning on.

This is called an instance initializer block, more information here.

like image 81
alpian Avatar answered Sep 23 '22 18:09

alpian