簡體   English   中英

如何刪除arraylist的最后一個元素

[英]How to remove last element of arraylist

我嘗試每10分鍾刪除一次arraylist的最后一個元素。 我正在使用此代碼來做到這一點:

final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {       
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {       
               array.remove(array.size() -1);   //array is my ArrayList object

            }
        });
    }
};

timer.schedule(doAsynchronousTask, 0, 600000); //execute in every 10 minutes

但是它給了IndexOutOfBoundsException 。任何人都可以解決這個問題。

之所以得到IndexOutOfBounds,是因為您試圖刪除不存在的項目,因此,如果其中沒有任何內容,則應該對刪除進行檢查以停止刪除:

if(array.size() > 0){
    array.remove(array.size() -1);
}

您有一個空數組,如@TheAndroidDev所說。 如何使用Rx,如下所示:

Observable.from(array)
            .interval(10, TimeUnit.MINUTES)
            .map(i -> array.size() > 0 ? array.remove(array.size() - 1) : null)
            .take(array.size())
            .subscribe(integer -> {
                // Do something with the integer or type you use
            });
     //check if its null or not when debugging
      if(array!=null){
        //Log something thats it is not null at this point
         if(array.size()>0){
               array.remove(array.size() -1);
           }
         else{ 
             //Log the array is empty 
           }
       } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM