-3

Not a duplicate of 'No suitable constructor found for' nor of 'No Suitable Constructor'.

My aim is to convert an array to an arrayList. I have had a look at Create ArrayList from array

So I tried:

ArrayList<Integer> al = new ArrayList<Integer>(Arrays.asList(arr));

where arr is an integer array.

On compiling, I got:

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

So I looked at the docs and found a constructor:

ArrayList(Collection<? extends E> c)

Since ArrayList<Integer>remaining = new ArrayList<Integer>(new Stack<Integer>()); compiled without errors, I inferred that passing a List<> (and perhaps any other subinterface of Collection) would result in an error, while any class that implemented Collection would compile.

The OP of Create ArrayList from array had asked:

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this array into an object of the ArrayList class.

ArrayList<Element> arraylist = ???;

which is exactly what I want to do.

Why did the accepted answer:

new ArrayList<>(Arrays.asList(array))

work for that OP but not for me? Am I overlooking something very small?

EDIT: I had forgotten the keyword 'new'. Added it now. Same error

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
rahs
  • 1,759
  • 2
  • 15
  • 31

1 Answers1

2

You are passing an int[] to Arrays.asList(), which means it returns a List<int[]>, which is not acceptable for the constructor of an ArrayList<Integer>.

If you were creating an ArrayList<int[]>, the following would work:

ArrayList<int[]> al = new ArrayList<int[]>(Arrays.asList(arr));

However, I don't think that's what you wanted. You should probably start with an Integer[] instead of an int[]. Then Arrays.asList() would produce a List<Integer>, which can be passed to ArrayList<Integer> constructor.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    IMHO `ArrayList al` is not something worth recommending... talking about programming to interfaces. – Naman Dec 24 '18 at 11:59