java List remove(Object object) 何时以及为何返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16120378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:57:46  来源:igfitidea点击:

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

javalist

提问by Luke Taylor

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

该方法何时以及为何boolean java.util.List.remove(Object object)返回 false?

The documentation states

该文件指出

[The method returns] true if this List was modified by this operation, false otherwise.

[该方法返回] 如果此 List 被此操作修改,则为 true,否则为 false。

Why wouldn't the operation take effect on the List?

为什么操作不会对List生效?

(NB: The implementation of the List I am making use of is the ArrayList)

(注意:我正在使用的 List 的实现是ArrayList

Update:The objects I am trying to remove do exist in the List. I add the class to the List(hence the argument this) and pass this(within the same class) to the remove method. Therefor the object should exist in the List (or not?).

更新:我试图删除的对象确实存在于列表中。我将类添加到List(因此是参数this)并将this(在同一类中)传递给 remove 方法。因此该对象应该存在于列表中(或不存在?)。

Update:Here is the code. Have a look at the delay()method. There is where I attempt to remove the respective class from the List.

更新:这是代码。看看delay()方法吧。在那里我尝试从List.

public class Timer extends Object {

    private static List<Timer> allTimers;
    private Long startTime;
    private int delayTime;
    private boolean registered;

    String name;

    public Timer(String name) {
        this.name = name;
        this.registered = true;
        allTimers.add(this);
        Log.d("SpaceDroid", "Foo: Created timer: " + name + " Size: " + this.allTimers.size());

    }

    public Timer(String name, int delayTime) {
        this(name);
        this.delayTime = delayTime;

    }

    public void setDelayTime(int delayTime) {
        this.delayTime = delayTime;

    }

    public boolean delay() {
        if(this.startTime == null) {
            this.startTime = System.currentTimeMillis();
        }

        if(startTime + this.delayTime < System.currentTimeMillis()) {
            if(this.registered) {
                Log.d("SpaceDroid", "Foo: Trying to remove timer: " + name);
                if(this.allTimers.remove(this)) {
                    Log.d("SpaceDroid", "Foo: Successfully removed timer: " + name);
                }
                else {
                    Log.d("SpaceDroid", "Foo: Did not remove timer: " + name);
                }

            }
            return true;

        }
        else {
            return false;

        }

    }

    // The same as resume, just renew the startTime

    public void reset() {
        this.startTime = null;
        this.registered = true;
        this.allTimers.add(this);

    }

    public void resume() {
        this.startTime = System.currentTimeMillis();

    }

    public void pause() {
        // Check if timer is still running
        if(!this.delay()) {
            // Calculate new delayTime
            delayTime = (int) ((startTime + this.delayTime) - System.currentTimeMillis());
            Log.d("SpaceDroid", "Foo: New delay time: " + delayTime + " for timer: " + name);

        }


    }

    public static void resumeAllTimers() {
        List<Timer> timers = new ArrayList<Timer>(Timer.allTimers);
        for (Timer timer : timers) {
            timer.resume();
        }

    }

    public static void pauseAllTimers() {
        List<Timer> timers = new ArrayList<Timer>(Timer.allTimers);
        for (Timer timer : timers) {
            timer.pause();
        }

    }

    public static void disposeAllTimers() {
        Timer.allTimers.clear();
        Timer.allTimers = null;

    }

    public static void initializeAllTimers() {
        allTimers = new ArrayList<Timer>();

    }


}

回答by ddmps

If the Objectpassed in is not actually in the list, it wouldn't take any effect on the list and therefore return false.

如果Object传入的实际上不在列表中,则不会对列表产生任何影响,因此返回 false。

Edit (thanks Jai): The method uses the specific Objects equals()method to determine if it contains that object. So, if you have custom objects make sure you override the equals()method, and also the hashCode()(to maintain the general contract between the methods).

编辑(感谢 Jai):该方法使用特定的Objectsequals()方法来确定它是否包含该对象。因此,如果您有自定义对象,请确保您覆盖该equals()方法,以及hashCode()(维护方法之间的一般契约)。

回答by Jops

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

由于 List 是一个接口,因此它没有示例的具体实现。但是从 ArrayList 中获取,如果出现以下情况,它将返回false

  • you pass null and there's no null object in the list, or
  • you pass an object not found on the list
  • 您传递 null 并且列表中没有 null 对象,或者
  • 您传递了一个未在列表中找到的对象

From ArrayList.java

来自 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:

添加fastRemove的代码,为了完整性:

 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

回答by stinepike

from this doc

从这个文档

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

从此列表中删除第一次出现的指定元素(如果存在)(可选操作)。如果此列表不包含该元素,则它保持不变。更正式地,删除具有最低索引 i 的元素,使得 (o==null ? get(i)==null : o.equals(get(i))) (如果存在这样的元素)。如果此列表包含指定的元素(或等效地,如果此列表因调用而更改),则返回 true。