• == 和 equal 的区别

    == 和 equal 的区别

    • == 比较引用的地址
    • equel 比较引用的内容 (Object 类本身除外)
    1. String obj1 = new String("xyz");
    2. String obj2 = new String("xyz");
    3. // If String obj2 = obj1, the output will be true
    4. if(obj1 == obj2)
    5. System.out.printlln("obj1==obj2 is TRUE");
    6. else
    7. System.out.println("obj1==obj2 is FALSE");
    8. // It will print obj1==obj2 is False
    9. // If String obj2 = obj1, the output will be true

    默认的, equals() 方法实际上和 “==” 在 object 类里是一样的. 但是这个方法在每一个子类里都会被覆写用来比较引用的内容 (因为每个类都继承了 object 类并覆写了这个方法)

    1. String obj1 = new String("xyz");
    2. String obj2 = new String("xyz");
    3. if(obj1.equals(obj2))
    4. System.out.printlln("obj1==obj2 is TRUE");
    5. else
    6. System.out.println("obj1==obj2 is FALSE");
    7. Resultat: obj1==obj2 is TRUE