Weird behaviour when using Java ternary operator

后端 未结 3 2339
误落风尘
误落风尘 2021-02-19 20:49

When I write my java code like this:

Map map = new HashMap<>()
Long number =null;
if(map == null)
    number = (long) 0;
else
    numbe         


        
3条回答
  •  后悔当初
    2021-02-19 21:56

    I commented above suggesting that he ensure map never be null, but that does not help with the ternary problem. As a practical matter, it's easier to let the system do the work for you. He could use Apache Commons Collections 4 and its DefaultedMap class.

    import static org.apache.commons.collections4.map.DefaultedMap.defaultedMap;
    
    Map map = ...;  // Ensure not null.
    Map dMap = defaultedMap(map, 0L); 
    

    Google Guava doesn't have anything as easy as that, but one can wrap map with the Maps.transformValues() method.

提交回复
热议问题