String test1 = "test";
String test2 = "test";
System.out.println(test1 == test2); // true
test1和test2指向同一个对象,所以结果为true。
String test1 = new String("test");
String test2 = new String("test");
System.out.println(test1 == test2); // false
test1 和 test2 指向不同的对象,因此结果为 false。
所以问题是,有什么区别,
int[] test = {1,2,3}; // literal
int[] test = new int[] {1,2,3}; // non-literal
我对此感到困惑,
int[] test1 = new int[]{1,2,3};
int[] test2 = new int[]{1,2,3};
System.out.println(test1 == test2); // false
和
int[] test1 = {1,2,3};
int[] test2 = {1,2,3};
System.out.println(test1 == test2); // also prints false
我预计后一种情况的结果是 true,与上面 String 示例的情况相同。
test1 和 test2 是否指向不同的数组对象?
最佳答案
Java int[]
永远不会 intern'd 。仅String
(以及有限值的包装类型)。 tl;dr 不要将对象相等性与 ==
进行比较。这仅将引用与实例类型进行比较。这里数组相等可以用 Arrays.equals(int[], int[])
来确定和 String
与 String.equals
。数组不会覆盖 Object#equals(Object)
。
int[] test1 = { 1, 2, 3 };
int[] test2 = { 1, 2, 3 };
System.out.println(Arrays.equals(test1, test2)); // <-- true
System.out.println(test1.equals(test2)); // <-- false
至于为什么它们不同 - Java String
是不可变的(原始类型也是如此)。在这里,我们可以更改其中一个数组中的值。如果对方也发生了变化,我们(作为用户)会感到惊讶。
关于java - java文字数组声明和new方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49318419/