I recognise this as uni homework. So I'm not attempting to give you the solution, but rather point you in the right directions.
Recursion
If I were to guess, I would say the objective of this assignment is to get you to use recursion, because that's the only alternative to iteration in solving a problem like this.
The clue was in the constructors:
ListA( A first, IListA rest )
and
ListB( B first, IListB rest )
Recursion is where a method calls itself directly (or indirectly), and stops doing so when a base case is encountered. Here are some examples.
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.
Use instanceof
In order to differentiate the two types of IListB's (EmptyListB and ListB), you could use instanceof. Given the variable list is an IListB (but you need to find out which one it implements):
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
}
Best practices
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:
- Give all your classes and the member variables and methods modifiers such as private, protected and public
- Create getters (and where needed setters too) for member variables of one class that need to be accessed from (objects of) other classes
- Adding (just enough) comments
Edit
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.
interface IListB {
public boolean isEmpty();
}
class EmptyListB implements IListB {
...
public boolean isEmpty()
{
return true;
}
}
class ListB implements IListB {
...
public boolean isEmpty()
{
return false;
}
}