0

I have array of integers. I can convert it using loop, like that:

    int[] test = {5, 3, 6, 10};
    List <Integer> intList2 = new ArrayList<>();
    for (int i : test){
        intList2.add(i);
    }
    for (int y : intList2){
        System.out.println(y);
    }

But I am trying to fill ArrayList using methods, and I have no success.

    int[] test = {5, 3, 6, 10};
    List <Integer> integerList = new ArrayList(Arrays.asList(test));

    for (int i : integerList) {
        System.out.println(i);
    }

It says:

Exception in thread "main" java.lang.ClassCastException: class [I cannot be cast to class java.lang.Integer ([I and java.lang.Integer are in module java.base of loader 'bootstrap') at Scratch.main(scratch_2.java:8)

I understand that there is a cast error. But i don't get how to solve it using for-each loop. But even if I use classic for loop, it still gives me not the result I expect.

        int[] test = {5, 3, 6, 10};
    List <Integer> integerList = new ArrayList(Arrays.asList(test));

    for (int i = 0; i < integerList.size(); i++) {
        System.out.println(integerList.get(i));
    }

The resulst is:

[I@1b28cdfa

Which is different from original integers. So I assume this line

    List <Integer> integerList = new ArrayList(Arrays.asList(test));

works incorrect. I've checked many articles on SO, but could not find answer. I would really appreciate if you can help me to understand that issue.

Can I somehow convert Array to ArrayList without using loops at all? I guess that without loops code looks cleaner.

1 Answers1

0

Try this: (java >= 9 & apache commons lang 3) (the array of primitives was converted to an array of objects)

List<Integer> integers = List.of(org.apache.commons.lang3.ArrayUtils.toObject(test));
System.out.println(integers);

result:

[5, 3, 6, 10]

or, with java 8:

List<Integer> integers = Arrays.asList(org.apache.commons.lang3.ArrayUtils.toObject(test));
System.out.println(integers);

result:

[5, 3, 6, 10]
Dan Chirita
  • 119
  • 9