Map.get() optimization in ?: ternary operator

后端 未结 3 902
礼貌的吻别
礼貌的吻别 2021-01-22 10:33

Consider the following code:

java.util.Map map = new java.util.HashMap();
...
String key = \"A\";
String value = map.         


        
3条回答
  •  难免孤独
    2021-01-22 11:17

    Your second option which is :

    String value = map.get(key);
    if(value == null) {
        value = "DEFAULT_VALUE";
    }
    

    is better from first one reason:

    1. You dont create an extra reference "tmp"

    2. You dont execute else which you do as part of your ternary comparison.

提交回复
热议问题