Java arraylist cannot find constructor using arrays.aslist

I am using the Arrays.asList () method. contains () in my code, as shown in the top answer: How to check if an array contains a specific value? , so I'm going to use Arrays.asList () in the code.

However, the compiler rejects this following code. Is this because of using primitives for an array of primes, and not for a reference type? I don’t think so because of autoboxing, but I just wanted to check.

import java.math.*; import java.util.ArrayList; import java.util.Arrays; public class .... { public static void main(String[] args) { int[] primes = formPrimes(15); ArrayList<Integer> primes1 = new ArrayList<Integer>(Arrays.asList(primes)); // Rest of code... } public static int[] formPrimes(int n) { // Code that returns an array of integers } } 

I get one error, I can not find the symbol error.

symbol: constructor ArrayList (java.util.List)

location: class java.util.ArrayList ArrayList primes1 = new ArrayList (Arrays.asList (primes));

Basically, I have a function that returns an array of integers, and I want to convert it to a list of arrays, and I'm having problems using the ArrayList constructor.

+6
source share
3 answers

Yes. Autoboxing does not apply to arrays, but only to primitives.

The error I get in eclipse, The constructor ArrayList<Integer>(List<int[]>) is undefined

This is because the constructor in ArrayList is defined as public ArrayList(Collection<? extends E> c) . As you can see, it accepts only the Collection subtype, which is not.

Just change your code to:

 public class .... { public static void main(String[] args) { Integer[] primes = formPrimes(15); ArrayList<Integer> primes1 = new ArrayList<Integer>(Arrays.asList(primes)); // Rest of code... } public static Integer[] formPrimes(int n) { // Code that returns an array of integers } } 

and everything should be fine, assuming you are returning an Integer array from fromPrimes .

Update From Andrew's comments, and after looking at the source of Arrays.asList:

 public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); } 

So what really happens is that Arrays.asList(new int[] {}) will actually return List<int[]> , unlike Arrays.asList(new int[] {}) which will return List<Integer> . Obviously, the ArrayList constructor will not accept List<int[]> , and therefore the compiler complains.

+6
source

primes - an array of primitive type int ; this type is not inferred from Object and therefore can be automatically placed in a List (which, like all Collections , can only hold Object s). @ Justin is right; you need to manually add elements from your array to the list.

+1
source

If you do this to access the content you can write your own.

 public boolean contains(int[] array, int item) { for (int element: array) if (element == item) return true; return false; } 
0
source

Source: https://habr.com/ru/post/917229/


All Articles