java - Implementation of toString() method in a linkedList -
i trying implement method prints out contents inside linked list.
here explanation of classes use:
1) nonemptylistnode
, emptylistnode
inherit abstractlistnode
.
2) trailing node represented emptylistnode
.
i implemented it, however, felt bad since taught instanceof
keyword bad. here questions:
1) can implement tostring() without instanceof
keyword?
2) implement tostring() in recursive way?
here code:
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) { (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 no 'item' value stored in emptylistnode."); } public abstractlistnode next() { throw new illegalargumentexception ("no elements follow emptylistnode."); } public boolean isempty() { return true; } @override public int size() { return 0; } @override public string tostring() { return ")"; } }
you can replace
iter instanceof nonemptylistnode
with
iter.isnonempty()
or
!iter.isempty()
where returns true
nonemptylistnode
Comments
Post a Comment