2

I was trying to implement a method that prints out the contents inside a linked list.
Here is an explanation of classes that I use:

1) NonEmptyListNode and EmptyListNode inherit AbstractListNode.
2) a trailing node is represented with the EmptyListNode.

I actually implemented it, however, I felt bad since I was taught that instanceof keyword is bad. Here are my questions:

1) Can I implement toString() without instanceof keyword?
2) Could I implement toString() in a recursive way?

Here is my 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) { 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 ")"; } } 
1
  • The EmptyListNode class is rather peculiar. Most implementations of linked lists don't require a special class for the terminator. Commented Feb 8, 2016 at 3:18

1 Answer 1

1

You can replace

iter instanceof NonemptyListNode 

with

iter.isNonEmpty() 

or

!iter.isEmpty() 

where this returns true for NonemptyListNode

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I didn't notice that I already had the method that I needed. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.