我正在尝试在对象上实现 Iterable 接口,其中迭代器上的 hasNext 方法将依赖于可变对象状态,该状态在调用每个 next 后通过显式函数调用而改变。 基本上我正在做这样的实现,以使其在多个实现中保持一致。-
public class MutableObject implements Iterable<MutableObject> {
String personId;
boolean initialCall;
String tokenId;
public MutableObject(String personId) {
this.personId = personId;
this.initialCall = true;
}
public MutableObject(String personId, boolean initialCall, String tokenId) {
this.personId = personId;
this.initialCall = initialCall;
this.tokenId = tokenId;
}
public void updateState(String tokenId) {
this.initialCall = false;
this.tokenId = tokenId;
}
private MutableObject currentState() {
return this;
}
private class MutableObjectIterator implements Iterator<MutableObject> {
@Override
public boolean hasNext() {
return initialCall || Objects.nonNull(tokenId);
}
@Override
public MutableObject next() {
if(!hasNext()) {
throw new NoSuchElementException("No more elements");
}
return currentState();
}
}
@NotNull
@Override
public Iterator<MutableObject> iterator() {
return new MutableObjectIterator();
}
可以这样调用:
public static void main(String[] args) {
MutableObject mutableObject = new
MutableObject(UUID.randomUUID().toString());
int count = 0;
String prevToken = null;
Iterator<MutableObject> itr = mutableObject.iterator();
while (itr.hasNext()) {
MutableObject currState = itr.next();
System.out.printf("[%d]: Curr State: %s\n", count,
currState.toString());
if(++count < 5) {
prevToken = "DUMMY_TOKEN";
} else {
prevToken = null;
}
currState.updateState(prevToken);
}
}
}
在我看来,代码看起来不错。但是,我要替换的是以下行:
Objects.nonNull(tokenId)
作者:
tokenId != null
为什么?因为它更容易阅读。