Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I recognise this as uni homework. So I'm not attempting to give you the solution, but rather point you in the right directions. </p> <p><strong>Recursion</strong> </p> <p>If I were to guess, I would say the objective of this assignment is to get you to use <strong>recursion</strong>, because that's the only alternative to <strong>iteration</strong> in solving a problem like this. </p> <p>The clue was in the constructors: </p> <pre><code>ListA( A first, IListA rest ) </code></pre> <p>and </p> <pre><code>ListB( B first, IListB rest ) </code></pre> <p>Recursion is where a method calls itself directly (or indirectly), and stops doing so when a <em>base case</em> is encountered. Here are <a href="http://danzig.jct.ac.il/java_class/recursion.html" rel="nofollow noreferrer">some examples</a>.<br> In this situation, where you have a data structure where X contains another instance of X lends itself quite well to the application of recursion insolving the problem. </p> <p><strong>Use instanceof</strong> </p> <p>In order to differentiate the two types of <code>IListB</code>'s (<code>EmptyListB</code> and <code>ListB</code>), you could use <code>instanceof</code>. Given the variable <code>list</code> is an IListB (but you need to find out which one it implements): </p> <pre><code>if (list instanceof ListB) { ListB listB = (ListB)list; //do stuff with listB } else if (list instanceof EmptyListB) { EmptyListB emptyListB = (EmptyListB)list; //do stuff with emptyListB } </code></pre> <p><strong>Best practices</strong> </p> <p>You code listing above, while technically correct, doesn't have much by way of good programming practices. You will find your code alot less unwieldy (and easier to work with yourself), by doing the following: </p> <ul> <li>Give all your classes and the member variables and methods modifiers such as private, protected and public</li> <li>Create getters (and where needed setters too) for member variables of one class that need to be accessed from (objects of) other classes</li> <li>Adding (just enough) comments</li> </ul> <h3>Edit</h3> <p>As per Rasmus' suggestion: Create isEmpty methods as follows, and then you can test whether an object of type IListB is empty or not rather easily.</p> <pre><code>interface IListB { public boolean isEmpty(); } class EmptyListB implements IListB { ... public boolean isEmpty() { return true; } } class ListB implements IListB { ... public boolean isEmpty() { return false; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload