Question

I have the following code:

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;
    }

Before the error, S is an int array { 2 }. It errors when I set TEST to Arrays.asList(S):

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

Why is this happening? I thought primitives were autoboxed?

Was it helpful?

Solution

Have a look at this bug report which was closed as Not an Issue citing the below reason.

Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays.

Therefore, to convert your array to an list, you need to do this

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

OTHER TIPS

Primitives are autoboxed but arrays are not. It will work if you change your int[]'s to Integer[]'s

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top