该方法何时以及为什么boolean java.util.List.remove(Object object)
返回 false?
该文件指出
[方法返回] 如果此 List 被此操作修改,则返回 true,否则返回 false。
为什么操作不会在 List 上生效?
(注意:我正在使用的 List 的实现是ArrayList
)
更新:
我试图删除的对象确实存在于列表中。我将类添加到List
(因此是参数this
)并将this
(在同一个类中)传递给 remove 方法。因此该对象应该存在于列表中(或不存在?)。
更新:
这是代码。看看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>();
}
}