I'm learning Java step by step. Now I know up to arrays, and next is Collections.
As I'm learning based on projects, I noticed that most of programmers choose to use Collections
rather than plain arrays to eliminate the loops and to make use of the predefined functions (like sort
and much more). So, first I'm trying to convert an int[]
into a Collection
. But I get an error in the foreach
loop...
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Coll {
public static void main(String[] args) {
Coll obj = new Coll();
obj.op();
}
void op() {
System.out.println("To convert Array to Collections");
Scanner getinp = new Scanner(System.in);
System.out.println("Enter the size of array : ");
int siz = getinp.nextInt();
int[] arry = new int[siz];
System.out.println("Enter the values of elements");
for (int i = 0; i < arry.length; i++) {
System.out.println("arry[" + i + "] : ");
arry[i] = getinp.nextInt();
}
List arrycoll = Arrays.asList(arry);
for (String elem : arrycoll) {
System.out.println(elem);
}
}
}
The error is in the following line:
for(String elem : arrycoll)
Pointing to arrycoll
, it states:
required `String` but found `Object`
If I define the arry
as String
and store String
s, it wouldn't be a error, but for int
it's not working..