gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:35:19 24 4
gpt4 key购买 nike

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

文档说明

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

为什么操作在List上不生效?

(注意:我正在使用的列表的实现是ArrayList)

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

更新:这是代码。看一下 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>();

}


}

最佳答案

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

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

关于java - List remove(Object object) 何时以及为何返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57523282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com