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:

Q. 1
Why are all the methods in NodeMethods.java static?



Exercise 3

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