Java == vs equals()
==比较的是:是否obj1和obj2在同一个内存.相比下,equals就是比较内容. 所以Object 要override equals()
/*Integer vs Integer*/ Integer a = new Integer(256); Integer b = new Integer(256); System.out.println(a == b); //false System.out.println(a.equals(b)); // true /*Integer vs int*/ Integer a1 = new Integer(256); int b1 = 256; System.out.println(a1 == b1); //true (这里证明了, a1的内存地址和b1是一样的// ) System.out.println(a1.equals(b1)); //true /*Integer deep copy*/ Integer a2 = new Integer(256); Integer b2 = new Integer(a2); System.out.println(a2 == b2); //false (因为做了deep copy) System.out.println(a2.equals(b2)); // true /*int vs Integer*/ int a3 = 256; Integer b3 = new Integer(a3); System.out.println(a3 == b3); //true (这个a3 pass 进去的不是object, 所以b3把a3当常量, 没有单独申请地址) System.out.println(b3.equals(a3)); // true
Leave A Comment