标签:
开发过程中我们经常会用到三目运算符,那下面的的两种情况你能说一下那种更合理吗
用法A:
...
Map<String Integer> result = new HashMap<String,Integer>()...
...
Integer count = result.get(key);
count == null ? result.put(key,1) : result.put(key,count++);
...
用法B:
...
Map<String Integer> result = new HashMap<String,Integer>()...
...
Integer count = result.get(key);
result.put(key,count==null ? 1 : count++);
...
乍一看,用法B更精炼,用法A更清晰。其实你错了,用法A是错误的,不信你就敲一下代码吧,呵呵。
原因是什么,一下子你可能想不到,其实很简单 三目运算符是有返回结果的,A错误的原因是少了左值表达式,根本就不能编译通过。
写代码多年的你是不是也又有点晕呢,看来写代码不能想当然,还是要多推敲呀。
标签:
原文地址:http://www.cnblogs.com/feiyue99/p/4691579.html