为什么Integer的两个引用等于某一点?

时间:2015-10-07 07:07:55

标签: java integer heap wrapper immutability

为什么Integer对象的行为与String对象的行为不一样?

我读到原因是性能,但无法理解它会如何表现更好?

请查看以下代码:

public class MyClass{
    public static void main(String[] args){
        String one = "myString";
        String two = "myString";
        System.out.println(one == two); // true

        String oneLong = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus in leo at massa vehicula rhoncus quis eu mauris. Pellentesque non nulla convallis, tempus augue sed, sollicitudin risus. Aenean posuere nulla ipsum, at faucibus massa dignissim non. Duis felis felis, iaculis eu posuere id, elementum id nulla. Fusce tristique arcu vitae consectetur vehicula. Mauris tincidunt nunc placerat tortor rhoncus, eget venenatis felis dapibus. Sed scelerisque ligula congue ligula elementum hendrerit. Proin et mauris vestibulum, rutrum ante ut, sollicitudin massa. Fusce tempus mattis eleifend. Phasellus ut ante turpis. Suspendisse eu leo nec elit ornare rhoncus sed nec ex. In at tellus mi.";
        String twoLong = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus in leo at massa vehicula rhoncus quis eu mauris. Pellentesque non nulla convallis, tempus augue sed, sollicitudin risus. Aenean posuere nulla ipsum, at faucibus massa dignissim non. Duis felis felis, iaculis eu posuere id, elementum id nulla. Fusce tristique arcu vitae consectetur vehicula. Mauris tincidunt nunc placerat tortor rhoncus, eget venenatis felis dapibus. Sed scelerisque ligula congue ligula elementum hendrerit. Proin et mauris vestibulum, rutrum ante ut, sollicitudin massa. Fusce tempus mattis eleifend. Phasellus ut ante turpis. Suspendisse eu leo nec elit ornare rhoncus sed nec ex. In at tellus mi.";
        System.out.println(oneLong == twoLong); // true

        Integer first = 1;
        Integer second = 1;
        System.out.println(first == second); // true

        Integer third = 500;
        Integer fourth = 500;
        System.out.println(third == fourth); // false
    }
}

以下是我发现的问题但没有回复:

Why Integer In Java is Immutable

Is Integer Immutable?

1 个答案:

答案 0 :(得分:1)

将对象保持为尽可能不可变通常是一个好主意,因为在多线程环境中可以毫无问题地共享不可变对象。

可以创建相同Integer的n份副本,副本是不可变的。请注意,对于String也可以创建相同String的n个不同副本。为此,您需要明确使用new关键字。

如果与operator ==返回true,则两个对象相同。如果与方法equals返回true相比,则两个对象具有相同的内容。

obj1 == obj2       // if true obj1 and obj2 are the same
obj1.equals(obj2)  // if true obj1 and obj2 have the same content 
                   // (can be the same or not)

在你的例子中,你有两个具有相同内容的Integer(所以equals返回true)但不同的内存位置(所以==返回false)