Declare and put a String array in a HashMap in one step

I am trying to insert static data into a HashMap in Java as follows:

HashMap<String,String[]> instruments = new HashMap<String, String[]>(); instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"}); 

But he does not like the compiler. The only way I found to insert this data into a HashMap is to declare an array of strings separately and then put it in a HashMap, for example,

 String[] instruDetails = {"4001","EURUSD","10000","0.00001","0.1","USD"}; instruments.put("EURUSD", instruDetails); 

But it is not very expressive and difficult to maintain.

So my question is: is there a way to do a put() operation and declare an array in one step / line?

+4
source share
3 answers

This will be done:

 instruments.put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"}); 
+11
source

To get all this in a single sentence, use initialization with double brackets: -

  HashMap<String,String[]> instruments = new HashMap<String, String[]>() { { put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"}); put("EUR", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"}); } }; 
+8
source

I think you already have what works. But the reason why

 instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"}); 

does not work because {"4001","EURUSD","10000","0.00001","0.1","USD"} . {} is syntactic sugar or a short shorthand in a Java array for initialization. It comes with the restriction that it should always go along with the statement of the declaration of the array, otherwise it is a syntax error.

Array declaration statement, e.g.

 String[] array = {"1", "2"}; 

Thus, Java knows that the array that it must create for you actually consists of elements of type String .

If you violate the above statement as follows

 String[] array; array = {"1", "2"}; 

It does not compile.

And with new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"} compiler knows that he must create an instance of a new array whose element type is String ( new String[] ) and initialize the newly created array with the values โ€‹โ€‹you specified ( {"4001","EURUSD","10000","0.00001","0.1","USD"} ).

+6
source

Source: https://habr.com/ru/post/1437856/


All Articles