Home > Blockchain >  Java Collections.unmodifiableList() compilation error: type convertion between raw type and boxed ty
Java Collections.unmodifiableList() compilation error: type convertion between raw type and boxed ty

Time:06-27

This code fails to compile:

        int[] values = new int[3];
        values[0] = 3;
        values[1] = 4;
        values[2] = 2;
        List<int> cu = Collections.unmodifiableList(Arrays.asList(values));

The error is in List<int>, it says:

Syntax error, insert "Dimensions" to complete ReferenceTypeJava(1610612976)

If I change to List<Integer> then error is in Collections.unmodifiableList(Arrays.asList(values)), saying:

Type mismatch: cannot convert from List<int[]> to List<Integer>Java(16777233)

How could I fix this problem?

CodePudding user response:

Just boxed it like below.

int[] values = new int[3];
values[0] = 3;
values[1] = 4;
values[2] = 2;
List<int> cu = Collections.unmodifiableList(Arrays.stream(ints).boxed().collect(Collectors.toList()));

CodePudding user response:

The Arrays.asList call is not doing what you're thinking. In your code, you're not creating a list of integers but a List<int[]> where each element is an array of int, as the compiler is saying.

To fix your problem, you first need to copy the elements of your array within a List and then create an UnmodifiableList from it.

Furthermore, generics only allow reference types as arguments for type parameters. int is a primitive type, so you cannot write List<int> but rather List<Integer>.

Here is a possible implementation which resolves your problem:

int[] values = new int[3];
values[0] = 3;
values[1] = 4;
values[2] = 2;
List<Integer> cu = Collections.unmodifiableList(Arrays.stream(values).mapToObj(i -> i).collect(Collectors.toList()));

CodePudding user response:

If you are using Java16 I would suggest to use toList():

List<Integer> cu = IntStream.of(values).boxed().toList();

Else from Java10 you can use IntStream and Collectors.toUnmodifiableList:

List<Integer> cu = IntStream.of(values)
        .boxed()
        .collect(Collectors.toUnmodifiableList());
  • Related