public class TestLogic { public static void main(String[] args) { List<String> listA = new ArrayList<String>(); listA.add("a"); List<String> listB = new ArrayList<String>(); // listB.add("b"); if((listA != null && listA.size() > 0) || listB != null && listB.size() > 0){ System.out.println("ok"); }else{ System.out.println("not ok"); } } }由于粗心导致
listB != null && listB.size() > 0
没有加上括号,本以为结果会有误差,但结果并没有影响
首先会执行 (listA != null && listA.size() > 0) 括号中的逻辑 这里结果为 true ,如果说 || 和 && 优先级相等或者 || 优先级大于 && ,这里会顺序执行 (listA != null && listA.size() > 0) || listB != null 这里结果也为true 然后再执行 listB.size() > 0 最后结果应为false ,输出 not ok 实际上输出结果 为 ok ,所以是先执行 (listA != null && listA.size() > 0) 再执行 listB != null && listB.size() > 0 ,所以结果为 true || false 结果为true ,输出 ok。以此验证 && 优先级大于 || 。
不过保险起见,这里 ( listB != null && listB.size() > 0 ) 用括号包围最佳!