代码的等价性

来源:互联网 发布:微博淘宝优惠券安全吗 编辑:程序博客网 时间:2024/04/29 11:59

代码片段1:

boolean result1 = file1.delete();boolean result2 = file2.delete();boolean result3 = file3.delete(); if( result1 || result2 || result3){    //do something ...}


 

代码片段2:

if( file1.delete() || file2.delete() || file3.delete()){    //do something ...}


 

上述两个代码片段是不等效的.在代码片段2,如果file1.delete()返回true,那么后面的file2.delete()file3.delete()将不会执行.在编程中需要避免这种陷阱!!!

 

完整示例如下:

public class LogicTest {    public void test1() {        System.out.println("call test1 begin ...");         Logic logic = new Logic();        boolean result1 = changeA(logic);        boolean result2 = changeB(logic);        boolean result3 = changeC(logic);         if (result1 || result2 || result3) {            System.out.println(logic.getA());            System.out.println(logic.getB());            System.out.println(logic.getC());        }         System.out.println("call test1 end ...");    }     public void test2() {        System.out.println("call test2 begin ...");         Logic logic = new Logic();        if (changeA(logic) || changeB(logic) || changeC(logic)) {            System.out.println(logic.getA());            System.out.println(logic.getB());            System.out.println(logic.getC());        }         System.out.println("call test2 end ...");    }     public boolean changeA(Logic logic) {        logic.setA(5);        return true;    }     public boolean changeB(Logic logic) {        logic.setB(6);        return true;    }     public boolean changeC(Logic logic) {        logic.setC(7);        return true;    }     class Logic {        private int a;        private int b;        private int c;         public int getA() {            return a;        }         public void setA(int a) {            this.a = a;        }         public int getB() {            return b;        }         public void setB(int b) {            this.b = b;        }         public int getC() {            return c;        }         public void setC(int c) {            this.c = c;        }    }     public static void main(String[] args) {        new LogicTest().test1();        System.out.println();        new LogicTest().test2();    }}


 

输出结果为:

call test1 begin ...567call test1 end ... call test2 begin ...500call test2 end ...


 

0 0
原创粉丝点击