Professional Documents
Culture Documents
Lab 1 F21
Lab 1 F21
Fall 2021
Lab 1
Each week there will be an exercise part and a lab part. You need to get checked off by
your TA for the lab part.
Exercise:
2. Now, you will rewrite the clone method such that it makes a deep copy of the
linked list (both nodes and the elements of the copy will be independent from the
original list’s.) First try the following two steps:
(i) use the following code when making a new Node that is a copy of the node
referenced by variable walk:
Node<E> newNode = new Node<E>((E)(walk.getElement()).clone(),
null);
(ii) and, restrict type E in your class heading as follows since you want E to be
Cloneable:
If you try to compile this code you will get an error message saying that the
clone() is protected in class Object. This is because at this time all Java knows
that the generic type E is a descendent of class Object, and the clone() method in
Object class is protected.
Any class that implements this interface needs to define a public clone() method.
(iii) Now, you can write a deep clone() method in SinglyLinkedList by making
nodes as suggested before:
To test your deep clone() method, first define a simple Person class with two
instance variables name, and age. Let this class implement PubliclyCloneable and
provide a public clone() method by simply calling super.clone(). Then, make a
linked list of Person objects. Clone the linked list. And test to see if the Person
objects in the original list and the copy are really independent. For example, you can
change a Person object’s data in one list and see if it is changed or not in the copy.
Lab:
Add the following methods to the DoublyLinkedList class and test them by adding
appropriate statements into DLLDriver. Make sure to test all cases.