I have an Array like this:
int [] a = {1, 2, 3};
Now I want to modify it, so I convert it to an ArrayList:
ArrayList b = new ArrayList<>(Arrays.asList(a));
However, I cannot remove an element from it. I tried:
b.get(0).remove(2);
Which didn’t work, seems b contains an object rather than integers? How can I remove an element from b?
>Solution :
You cannot use Arrays.asList() with an array of primitive type like int[] as parameter, as this will create a list containing an array itself, meaning List<int[]> instead of List<Integer>. This would only work with an array of objects (Integer[] for example).
More info: Arrays.asList() not working as it should?
To create a List this way, you could use streams:
List<Integer> b = Arrays.stream(a).boxed().collect(Collectors.toList());
(please not that you cannot use generics with primitives as types).
The result in b can be modified.
Then: you can either call b.get(0) to retrieve the first element of the list – it returns a number, not a list.
Or you call b.remove(2) to delete the third element of the list. It will return the removed element or throw an IndexOutOfBoundsException.