我试图实现一种打印出链表中内容的方法。
以下是我使用的类的说明:
1)NonEmptyListNode
和EmptyListNode
继承AbstractListNode
。
2) 尾随节点用EmptyListNode
表示。
实际上实现了它,但是,自从我被告知instanceof
关键字不好以来,我感觉很糟糕。以下是我的问题:
1) 我可以在没有instanceof
关键字的情况下实现 toString() 吗?
2)我可以以递归的方式实现toString()吗?
这是我的代码:
abstract public class AbstractListNode {
abstract public Object item();
abstract public AbstractListNode next();
abstract public boolean isEmpty();
abstract public int size();
abstract public String toString();
}
class NonemptyListNode extends AbstractListNode {
private Object myItem;
private AbstractListNode myNext;
public NonemptyListNode (Object item, AbstractListNode next) {
myItem = item;
if (next == null) {
myNext = new EmptyListNode();
} else {
myNext = next;
}
}
public NonemptyListNode (Object item) {
this (item, new EmptyListNode());
}
public Object item() { return myItem; }
public AbstractListNode next() { return myNext; }
public boolean isEmpty() {return false;}
@Override
public int size() {
return 1 + myNext.size();
}
@Override
public String toString() {
AbstractListNode iter = this;
String str = "( ";
//HERE
while(iter instanceof NonemptyListNode){
str += iter.item() + " ";
iter = iter.next();
}
return str + iter.toString();
}
}
class EmptyListNode extends AbstractListNode {
public EmptyListNode() {}
public Object item() {
throw new IllegalArgumentException ("There is no 'item' value stored in an EmptyListNode.");
}
public AbstractListNode next() {
throw new IllegalArgumentException ("No elements follow an EmptyListNode.");
}
public boolean isEmpty() {
return true;
}
@Override
public int size() {
return 0;
}
@Override
public String toString() {
return ")";
}
}
你可以替换
iter instanceof NonemptyListNode
跟
iter.isNonEmpty()
或
!iter.isEmpty()
这将返回true
NonemptyListNode