Arrays AsList Int Array Pitfall

Arrays.asList on an int[] builds a one-element List<int[]> instead of boxing: pass an Integer[] (or IntStream.boxed) for element-wise conversion.

JavaData Integrity

Code

snippet
import java.util.Arrays;
import java.util.List;

public class AsListVarargs {

    public static void main(String[] args) {
        int[] scores = {90, 75, 60};

        // asList(T...) 的 pitfall:收到 int[] 时 T 推断为 int[],
        // 整个 array 被当成唯一元素,得到长度 1 的 List<int[]>
        List<int[]> wrong = Arrays.asList(scores);
        System.out.println("wrong size: " + wrong.size());

        // 装箱成 Integer[] 才会按元素展开
        Integer[] boxed = {90, 75, 60};
        List<Integer> right = Arrays.asList(boxed);
        System.out.println("right size: " + right.size() + " first: " + right.get(0));

        // 或者直接用 List.of / IntStream.boxed 装箱
        List<Integer> ofList = List.of(90, 75, 60);
        System.out.println("of size: " + ofList.size());
    }
}

How it works

The code’s whole job belongs to the class AsListVarargs and the function main.

Watch out for

  • All of its symbols are language built-ins — nothing needs fetching.

Using it

Signature: public static void main(String[] args)

The run emits 3 labeled sections — wrong size:, right size:, of size: — one per step.

The key statements, annotated

List<Integer> right = Arrays.asList(boxed);
List<Integer> ofList = List.of(90, 75, 60);
List<int[]> wrong = Arrays.asList(scores);

Interactive Tools for This Topic

FAQ

What does Arrays AsList Int Array Pitfall print when run?
Invoke the file as-is — the `wrong size:`, `right size:`, `of size:` prefixes identify which step printed each line.