CSE 205 Spring 2017
Page 1
Practice Sheet
Question 1: Trace the output of the following code using the LinkedList and ListIterator class we
discussed in class. Write the output in the box provided.
public class LinkedListTester
{
public static void main(String[] args)
{
LinkedList list1 = new LinkedList();
ListIterator iterator = list1.listIterator();
iterator.add("Apple");
printList(list1);
iterator.add("Orange");
printList(list1);
iterator.add("Tomato");
printList(list1);
iterator = list1.listIterator();
iterator.next();
iterator.next();
iterator.add("Banana");
printList(list1);
iterator.next();
iterator.add("Lemon");
printList(list1);
iterator = list1.listIterator();
iterator.next();
iterator.remove();
while (iterator.hasNext())
System.out.println(iterator.next());
}
//This method prints out the content of LinkedList
public static void printList(LinkedList list1)
{
ListIterator iterator = list1.listIterator();
String result = "{ ";
while (iterator.hasNext())
result += iterator.next() + " ";
result += "}";
System.out.println(result);
}
}
{ Apple }
{ Apple Orange }
{ Apple Orange Tomato }
{ Apple Orange Banana Tomato }
{ Apple Orange Banana Tomato Lemon }
Orange
Banana
Tomato
Lemon
CSE 205 Spring 2017
Page 2
Question 2: What would be the output of the following program in the box? (5 pts)
public class MyClass {
public int myInt = 42;
public int[] myIntArray = {1, 2, 3, 4};
public MyClass myNext = null;
public String toString() {
String result = new String("");
result += myInt;
for (int i = 0; i<4; i++)
result +=(" " + myIntArray[i]);
return result;
}
public static void main(String[] argv) {
MyClass inst1 = new MyClass();
MyClass inst2 = new MyClass();
MyClass inst3 = inst1;
inst3.myNext = inst1;
inst2.myNext = inst3;
inst1.myIntArray[0] = 9;
inst2.myIntArray[1] = 11;
inst3.myIntArray[2] = 13;
inst1 = inst2;
inst2.myNext = inst1;
inst3.myNext = inst1.myNext;
inst1.myNext.myIntArray[3] = 15;
inst2.myNext.myInt =21;
inst3.myNext.myInt= 23;
System.out.println(inst1);
System.out.println(inst2);
System.out.println(inst3);
}// end main
}// end class
23 1 11 3 15
23 1 11 3 15
42 9 2 13 4