When and why does List remove(Object object) return false

后端 未结 3 1940
情歌与酒
情歌与酒 2020-12-19 21:27

When and why does the method boolean java.util.List.remove(Object object) return false?

The documentation states

[The method ret

3条回答
  •  暖寄归人
    2020-12-19 22:16

    Since List is an interface, it wouldn't have a concrete implementation for an example. But taking from ArrayList, it will return false if:

    • you pass null and there's no null object in the list, or
    • you pass an object not found on the list

    From ArrayList.java

         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;
         }
    

    Adding the code of fastRemove, for completeness:

     private void fastRemove(int index) {
          modCount++;
          int numMoved = size - index - 1;
          if (numMoved > 0)
              System.arraycopy(elementData, index+1, elementData, index,
                               numMoved);
          elementData[--size] = null; // Let gc do its work
      }
    

    Proving it:

    public static void main(String[] args) {
            ArrayList l = new ArrayList();
            System.out.println("Removing null on empty list: " + l.remove(null));
            System.out.println("Removing an object that won't be found: " + l.remove(new Object()));
    }
    

    Result:

    Removing null on empty list: false
    Removing an object that won't be found: false
    

提交回复
热议问题