【问题标题】:difference between java literal array declaration and with new methodjava文字数组声明和新方法之间的区别
【发布时间】: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 次,您对结果持怀疑态度?

标签: java arrays


【解决方案1】:

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 是不可变的(就像原始类型一样)。在这里,我们可以更改其中一个数组中的值。如果另一个也发生了变化,我们(作为用户)会感到惊讶。

【讨论】:

  • 谢谢,所以 int[] arr = {1,2,3};和 int[] arr = new int[]{1,2,3};内部没有区别吧? (与字符串相反)
  • @jwkoo new String(String) 是一个毫无意义的复制构造函数。您的两个 int[] 示例是相同的(第一个是第二个的语法糖)。
  • 对不起,“毫无意义”是什么意思?由于 String test = new String("o"); 的情况,那个 test String 变量指向字符串 "o"
  • @jwkoo String test = "o"; - 我们为什么要复制 String 文字?使用更多内存来复制不可变对象有什么意义?
  • 我无法理解您对“复制”的含义,stackoverflow.com/questions/3052442/… 说文字创建的字符串对象进入堆常量池,但非文字字符串对象进入堆。它完全不同。我认为这不仅仅是复制,而是创建新对象。
【解决方案2】:

声明数组两种方式都可以

int[] a = new int[] {1,2,3,4,5};
int[] b = {7,8,9,10};

但在声明之后,第一种方法可以将新数组分配给相同类型的现有变量,第二种方法没有。

a = new int[] {1,1,1,1};  // ok
b = {2,2,2,2,2};          // error: illegal start of expression

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2010-10-10
    相关资源
    最近更新 更多