【问题标题】:Making a copy of an array with Arrays.asList [duplicate]使用 Arrays.asList 制作数组的副本 [重复]
【发布时间】:2015-06-26 06:42:28
【问题描述】:

所以我有一个 int 数组,并希望有另一个数组指向与原始数组相同的值,这样当原始数组更改时,第二个数组将指向新值。

我试过了

List<Integer> secondList = new ArrayList<>(Arrays.asList(original array));
secondList = secondList.subList(start,finish);

但我收到一个错误,指出 .asList 返回 - 类型为 int[] 的列表 难道我做错了什么?或者有什么好的办法吗?

【问题讨论】:

  • 让我猜猜:原始数组被清除为int[]?尝试将其声明为Integer[]
  • @Turing85 你会怎么做呢?
  • @AnubianNoob 我不明白......就像其他所有数组一样:Integer[] array = new Integer[size];。您必须使用array[i] = new Integer(value); 初始化每个单元格。
  • 你不需要复制,你只是为了创建一个新的参考。

标签: java arrays collections


【解决方案1】:

如果原始数组是int[]Arrays.asList 将返回一个List&lt;int[]&gt;。如果原始数组为Integer[]Arrays.asList 将返回List&lt;Integer&gt;

【讨论】:

    【解决方案2】:

    您可以使用“=”运算符让第二个列表指向第一个。

    例如:

    List<Integer> firstList = new ArrayList<Integer>();
    List<Integer> secondList = firstList;
    
    firstList.add(1);
    System.out.println(secondList.size());
    

    将打印出“1”作为第二个列表的大小,因为它们都“指向”内存中的同一位置。

    【讨论】:

    • 第一个ist不是一个列表,而是一个数组。因此,您的解决方案将不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2015-06-09
    • 2017-07-03
    • 1970-01-01
    • 2019-11-16
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多