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

后端 未结 11 1420
一生所求
一生所求 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:02

    I think it would be faster to create a new ArrayList with just the first element inside. something like :

    E temp = mapOverlays.get(0);
    mapOverlays = new ArrayList<E>().add(temp);
    
    0 讨论(0)
  • 2020-12-17 10:02
    int size = mapOverlays.size();
    for(int n=0;n<size;n++)
    {
        mapOverlays.remove(n);
    }
    

    In java, if mapOverlays is list then it start with 0 as a first index.So n=0 in for loop.

    0 讨论(0)
  • 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<size;n++)
    {
        mapOverlay[n] = null;
    }
    

    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

    0 讨论(0)
  • 2020-12-17 10:07

    Why don't you try backwards?

    int size = itemizedOverlay.size();
    for(int n=size-1;n>0;n--)
    {
        mapOverlays.remove(n);
    }
    
    0 讨论(0)
  • 2020-12-17 10:09

    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
    
    0 讨论(0)
提交回复
热议问题