Immutable Lists
Chapter: Immutable Lists
Node.java is a very simple class implementing nodes with
int data. There is a constructor and just two accessor methods. There is
no provision for changing the fields of existing nodes: You must instead
create new nodes incorportating your desired changes. This kind of
node is very well-suited to a recursive style of programming.
Look in NodeMethods.java where you will see
a simple implementation of addLast that enables you to create a new
list from an existing list and an int. The new list will be the same as
the existing except that it has one extra node containing the new int at
the end.
Program Test1.java lets you test the immutable list
implementation. It builds the list 1 2 3 4 5 and then adds 6 to the end. Notice how both addlast and print naturally are written as
recursive methods:
- To print a nonempty list you need to:
- print the data in the first node;
- make a recursive call to print the rest of the list;
- To print an empty list, just print a newline character
- ..
- To add a new last entry to the empty list you just return a list
with a single node containing the data and a null reference.
- To add a new last entry to a nonempty list, you need to build a
new list:
- You want the same int data existing.getData()in the first node, but
- next should be as before but with the new int added at the end
- This is achieved recursively as addLast(newInt, existing.getNext())

- Q. 1
- Why are all the methods in NodeMethods.java static?
Add a method public static Node change(int from, int to, Node existing) to the class NodeMethods.java so that you return
a list just like existing except that
all occurrrences of from in the list existing will instead be
to. If your method is correct, it should behave like this when you
run Test2.java:
java Test2
1 3 5 7 9 11 13 15 17 19 1 3 5 7 9 11 13 15 17 19
1 3 5 7 9 11 0 15 17 19 1 3 5 7 9 11 0 15 17 19
rhyspj@gwu.edu