【问题标题】:Autoboxing not working? [duplicate]自动装箱不起作用? [复制]
【发布时间】:2013-10-16 11:13:22
【问题描述】:

我有以下代码:

static boolean nextPerm(int[] A) {
        int N = A.length;
        int k = N - 1;
        int[] S = { };
        while (k >= 0) {
            if (S.length > 0 && containsLarger(S, A[k])) {
                int v = firstLargest(S, A[k]);
                //int vIndex = Arrays.asList(S).indexOf(v);
                List<Integer> test = Arrays.asList(S); // // ERRORS HERE. Before error, S is { 2 } 
                System.out.println(test.get(0)); 
                int vIndex = test.indexOf(S);
                S[vIndex] = A[k];
                A[k] = v;
                System.arraycopy(S, 0, A, k + 1, N - k);
                return true;
            } else {
                S = addIntAscend(S, A[k]);
                k -= 1;
            }
        }
        return false;
    }

在出错之前,S 是一个 int 数组 { 2 }。当我将 TEST 设置为 Arrays.asList(S) 时出错:

Perms.java:44: error: incompatible types
                List<Integer> test = Arrays.asList(S);
                                                  ^
  required: List<Integer>
  found:    List<int[]>
1 error

为什么会这样?我以为原语是自动装箱的?

【问题讨论】:

    标签: java autoboxing


    【解决方案1】:

    看看这个bug report,它被关闭为Not an Issue,理由如下。

    整个数组的自动装箱不是指定的行为,永远 原因。对于大型阵列来说,它可能非常昂贵。

    因此,要将数组转换为列表,您需要这样做

    List<Integer> test = new ArrayList<Integer>(S.length);
    for (int i : S) {
        test.add(i);
    }
    

    【讨论】:

      【解决方案2】:

      基元是自动装箱的,但数组不是。 如果您将 int[]'s 更改为 Integer[]'s

      ,它将起作用

      【讨论】:

      • 但是看看这个例子。 stackoverflow.com/a/6171675/2288418 他将一个 int 数组传递给 asList 并能够获取它的索引。编辑:没关系,他的示例 LOL 中有一个错误。
      猜你喜欢
      • 1970-01-01
      • 2018-02-05
      • 2013-10-29
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      相关资源
      最近更新 更多