Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing an initialized static hashtable elegantly [duplicate]

Tags:

java

hashtable

Is there a way to write a static final Hashtable in java in key value pairs just like you can initialize a string array conveniently as :

String [] foo = {"A","AB"};

Basically what I mean is not having to write the words "put" for key:value pairs but instead may be something like:

Hashtable<String, String> foo = {"JJ":"222","KK":"222"}

which IMO looks more elegant.

(I know the initialization would need to be in a static block. I am leaving that out for now)

like image 704
I J Avatar asked Oct 15 '11 05:10

I J


People also ask

Is there a static initialization for a static HashMap?

The Static Initializer for a Static HashMap The advantage of this kind of initialization is that the map is mutable, but it will only work for static. Consequently, entries can be added and removed as and when required. Let's go ahead and test it:

What is a Hashtable and how to use it?

Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It generally optimized the lookup by calculating the hash code of every key and store into another basket automatically and when you accessing the value from the hashtable at that time it matches the hashcode with the specified key.

How many times can a static initialization block be called?

However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program.

How do Hashtables get their names when fully expanded?

The hashtables have a special syntax that looks like this when fully expanded. The name is what the cmdlet would label that column. The expression is a script block that is executed where $_ is the value of the object on the pipe. Here is that script in action:


1 Answers

An anonymous inner class would give you double brace initialization, which is useful in some cases:

static final Map<String, String> map = new HashMap<String, String>() {{
    put("foo", "bar");
    put("x", "y");
}};

In any case, @michael667's answer is probably the best

like image 59
brcosta Avatar answered Sep 18 '22 06:09

brcosta