Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove an element from a Array converted ArrayList?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading