Ternary operator of method execution

I have HashMap<Foo,ArrayList<Bar>>

and I want this when I get ArrayList

associated with a key and add some value to it.

The ternary operator does

I am currently checking if the value associated with the key Foo is null, if it then creates a new ArrayList add what I want and put it back on the map. If not, I save that arrayList adds what I want to it and put it back into the map again.

I could do it like this:

ArrayList<Bar> valuesList = map.get(key);
if(valuesList == null){
    valuesList = new ArrayList<Bar>;
}
valuesList.add(Item);
map.put(Foo,valuesList);

      

But I prefer to use the ternary operator to make my code a little shorter:

ArrayList<Bar> valuesList= (map.get(key) == null) ? new ArrayList<Bar>() : map.get(key);
valuesList.add(Item);
map.put(Foo,valuesList);

      

My question is: (in the second) example am I executing map.get(key)

twice? Or does the Java compiler know how and only evaluate it once? (I know this is a tiny difference in execution speed, but if it runs twice in half, I just need to start using example 1)

+3


source to share


3 answers


The following is what I would use, since you also wouldn't unnecessarily call put if the list is already in your map:

List<Bar> valuesList = map.get(key);
if(valuesList == null){
    valuesList = new ArrayList<Bar>();
     map.put(key,valuesList);
}
valuesList.add(Item);

      



Note, I find this to be much more readable than using the ternary operator (fewer lines of code isn't necessarily easier, IMHO). And depending on the size of your maps, keeping unnecessary calls (get and put) may not be trivial.

+3


source


Examining the bytecode reveals that the get () method is actually called twice in the second piece of code. It is theoretically possible that the map will change between calls, so this cannot be optimized.



On the other hand: your call to map.put () is redundant, because by changing the object, you are automatically changing the stored object in the map. You are not pulling a copy from the map, you are pulling an object reference from the map.

+2


source


Why not pass map.get (key) in a variable and then use it with the ternary operator?

You can do:

Object value = map.get(key);
ArrayList<Bar> valuesList = (value == null) ? new ArrayList<Bar>() : value;
valuesList.add(Item);
map.put(Foo,valuesList);

      

+1


source







All Articles