[java] 装箱拆箱机制造成的不相等问题

Java中存在装箱与拆箱机制

  • 装箱(Boxing)
    Integer I = 10;
    
  • 拆箱(Unboxing)
    int i = I;
    
  • 实际译为
    Integer I = Integer.valueOf(10);
    int i = I.intValue();
    

如果比较两个整数的包装类则发现

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i == j); //false,因为对象是两个

Integer m = 10;
Integer n = 10;
System.out.println(m == n); //true,因为对象有缓存

Integer p = 200;
Integer q = 200;
System.out.println(p == q); //false,因为对象是两个
  • 编译器会缓存[-128, 127]并且进行过装箱的整数,并进行拆箱

String对象的特殊性

  • 判断相等,一定不要用==,要用equals
  • 但是字符串常量(String literal)及字符串常量会进行内部化(interned),相同的字符串常量是==
    ``` String hello = “Hello”, lo = “lo”; System.out.println(hello == “Hello”); //true System.out.println(Other.hello == hello); //true

System.out.println(hello == (“Hel” + “lo”)); //true System.out.println(hello == (“Hel” + lo)); //false

System.out.println(hello == new String(“Hello”)); //false System.out.println(hello == (“Hel” + lo).intern()); //true ```

Written on December 3, 2022