Java List Remove時要注意的細節


1、如果你是在遍歷的時候去remove一個對象

  for(int i = 0, length = list.size(); i<length; i++){}

    這種遍歷需要每次remove時,對i--,也要對length--,或者i<list.size()

  for(Object o : list){}

    這種遍歷時,remove也是有問題的,需要去看下class文件的具體實現,待研究

       for(Iterator<T> it = list.iterator(); it.hasNext();){}

      這種遍歷時,remove也是有問題的,需要去看下源碼實現(AbstractList和remove方法)

 

2、remove(Object o),注意Object的equals實現

public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

  需要注意源碼中是用equals去判斷的,如果你的Object重寫了equals方法,就需要注意了。

       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM