Search code examples
javaarrayspass-by-reference

Add a content of an array as an element to a list in Java 11


I have rather a trivial question on which I am thinking without success.

Suppose we have a snippet of code like this:

int x[] = new int[]{3,4};

List<int[]> testList = new ArrayList<>();

testList.add(x.clone()); 
//testList.add(Arrays.copyOf(x,x.length)); -neither this works

System.out.println(testList);

the code prints: [[I@6442b0a6]

As I understand, in the code above I have passed a pointer of x to the testList. But I wanted to pass the content of x so that testList contain a copy of x as an element?

What's more I want to do it without explicit iteration over x.


Solution

  • The closest to your code:

    Integer[] x = {3, 4};
    List<Integer> testList = new ArrayList<>();
    Collections.addAll(testList, x); // Size 2.
    System.out.println(testList);
    

    As the List contains the Object class Integer the ints must be boxed to Integer.

    int[] x = {3, 4};
    List<Integer> testList = IntStream.of(x).boxed().collect(Collectors.toList());
    

    After clarification

    int[] x = {3, 4};
    List<int[]> testList = new ArrayList<>();
    testList.add(x);
    
    for (int[] y: testList) {
        System.out.println(Arrays.toString(y));
    }