2

Java compiler takes care of casting primitive data types and their wrapper classes..But my doubt is that although java compiler performs type casting all by itself, why is it that it prints an error when I try to convert an Array to ArrayList with int array as parameter..Like:

int[] val = {1,2,3,4,5};
ArrayList<Integer> newval = new ArrayList<Integer>(Arrays.asList(val));

Error: no suitable constructor found for ArrayList(List<int[]>)

Why is the compiler not casting int to Integer?

Derlin
  • 9,572
  • 2
  • 32
  • 53
Akshit Gupta
  • 109
  • 1
  • 8
  • 5
    There's no auto-boxing of primitive arrays to arrays of the corresponding wrapper type. – Eran Jan 11 '18 at 11:56
  • 3
    Using a `Stream` to convert `int` into a `Integer` then collect the all would be the simplest I guess... – AxelH Jan 11 '18 at 11:58
  • 1
    Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing but not collections to their respective in arrays format. – ArifMustafa Jan 11 '18 at 12:00

5 Answers5

2

You can use a IntStream to help you with the "boxing" of primitives

int[] a = {1,2,3,4};
List<Integer> list = IntStream.of(a)
        .boxed()
        .collect(Collectors.toList());

This will iterate the array, boxed the int into an Integer and then you just have to collect the Stream into a List with the Collectors.

AxelH
  • 14,325
  • 2
  • 25
  • 55
1

You can't create a ArrayList<primitive types> Source: why you can't create a Arraylist of primitive types. Instead, use an adaptor class:

class Adapter{

private int[] value;

adapter(int[] value){

this.value = value;
 }
 public int[] getValue(){
 return value;
   }
  }

And then add it to the ArrayList<Adapter> AL = new ArrayList<>();

Alex Cuadrón
  • 638
  • 12
  • 19
0

There is no autoboxing here; perhaps you meant to do:

Integer[] val = {1,2,3,4,5};
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • 1
    I guess the array initialization is just for the MCVE ;) but it could be that simple ... – AxelH Jan 11 '18 at 12:11
0
int[] val = {1,2,3,4,5};

For Primitive arrays:

List<int[]> vv = Arrays.asList(val); 

Will get List of arrays because autoboxing wont work when we try to convert the primitive array into list

For Object array type:

Integer[] val = {1,2,3,4,5};
List<Integer> vv = Arrays.asList(val); 

Compiler will use autoboxing

AxelH
  • 14,325
  • 2
  • 25
  • 55
sid
  • 11
  • 3
-2

Arrays.asList accepts an array of objects - not primitives (in many cases the compiler is smart enough to interchange through something called autoboxing - in this case not). Using a simple loop you can add the items of the array to the List.

Derlin
  • 9,572
  • 2
  • 32
  • 53
SF..MJ
  • 862
  • 8
  • 19