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

后端 未结 11 1505
一生所求
一生所求 2020-12-17 09:39

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

        
11条回答
  •  孤街浪徒
    2020-12-17 10:03

    If you are using a java.util.List implementation instead of array, the size of the array gets smaller everytime you remove something and the n+1 item replaces the n item. This code will eventually result to ArrayIndecOutOfBoundsException when n becomes greated than the last index in the list.

    Java also has an array type and the size of that one cannot be changed:

    Object[] mapOverlay = //initialize the array here
    int size = mapOverlay.length;
    for(int n=1;n

    I don't know PHP but this sounds like it's close to the behavior you are after. However the List implementations are more flexible and comfortable in use than the arrays.

    EDIT: Here's a link to the Javadoc of List.remove(int): http://java.sun.com/javase/6/docs/api/java/util/List.html#remove%28int%29

提交回复
热议问题