Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove everything from an ArrayList in Java but the first element

Tags:

java

arraylist

I am new to java programming, been programing in php so I'm used to this type of loop:

int size = mapOverlays.size();
for(int n=1;n<size;n++)
{
    mapOverlays.remove(n);
}

So I want to remove everything but the first item, so why doesn't this work? As I get it, after removal, array keys are rearranged or not?

like image 890
dfilkovi Avatar asked Sep 04 '25 02:09

dfilkovi


2 Answers

You could use

mapOverlays.subList(1, mapOverlays.size()).clear();
like image 103
Adam Crume Avatar answered Sep 07 '25 07:09

Adam Crume


As I get it, after removal, array keys are rearranged or not? Yes, the item which was on position 2 is on position 1 after you removed the item on position 1.

You can try this:

Object obj = mapOverlays.get(0); // remember first item
mapOverlays.clear(); // clear complete list
mapOverlays.add(obj); // add first item
like image 21
Daniel Engmann Avatar answered Sep 07 '25 06:09

Daniel Engmann