【发布时间】:2018-03-16 10:25:59
【问题描述】:
String test1 = "test";
String test2 = "test";
System.out.println(test1 == test2); // true
test1 和 test2 指向同一个对象,所以结果为真。
String test1 = new String("test");
String test2 = new String("test");
System.out.println(test1 == test2); // false
test1 和 test2 指向不同的对象,所以结果为假。
所以问题是,有什么区别,
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
我预计后一种情况的结果是正确的,与上面字符串示例的情况相同。
test1 和 test2 是否指向不同的数组对象?
【问题讨论】:
-
String 和 int 不一样。 stackoverflow.com/questions/2486191/…
-
int[] test1 = {1,2,3};每次都会创建一个新数组。 -
@Murat K. 我已经读过那篇文章。我知道 String 和 int 不一样。但它的 int 数组。所以 test1 指向堆区域中的那个数组。我错了吗?
-
@assylias 用 String 类以字面方式创建字符串对象会覆盖前一个,但不会覆盖以字面方式创建的数组对象?
-
for 循环会不会让读者感到困惑?您是否相信结果可能会随着时间而改变,JVM 可能会意识到,如果您重复同样的问题 3 次,您对结果持怀疑态度?