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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With