Pass by Value 2 COSC 112, Spring 2019 Lecture 09 Friday, March 1 2019 Scott Alfeld Announcements Recall: Midterm will be Friday, March 8 In class -- usual time, usual room. I will be out of town. If you have accommodations you’d like to use: Email me Today! Today: Using object references Consider the following code: int myArray[] = new int[100]; for (int i = 0; i < myArray.length; i ++){ myArray[i] = getIntFromUser(); } for (int i = myArray.length - 1; i >= 0; i --){ System.out.println(myArray[i]); } A thought experiment Suppose Java didn’t have arrays. Specifically: Instead of: ● I want to be able to iterate over int myArray = {2, 4, 8}; all the ints. I could: ● I want to be able to hold int i1 = 2; int i2 = 4; int i3=8; arbitrary ints (not, e.g., just But what if I want 100 ints? powers of 2) How can I achieve that with < 100 lines of code? Your task: Without using arrays, ArrayLists, Vectors, etc.: Create a class, IntHolder, which stores ints. It lets me: ● add a new int ● print all the ints I’ve ever added (in reverse order of how I added them) After that: ● Make it a SphereHolder, holding Spheres instead of ints ● Instead of printing, it can call mySphere.update() on each ● Add the ability to remove an element A solution: class Node{ Sphere s;//int num Node next; public Node(Sphere s){ this.s = s; } } public class SphereHolder{ Node end; public SphereHolder(){ end = null; } } public void append(Sphere toAppend){ Node toAdd = new Node(toAppend); toAdd.next = end; end = toAdd; } public Sphere peek(){ return end.s; } public Sphere pop(){ Sphere toReturn = end.s; end = end.next; return toReturn; } public void update(){ Node n = end; while (n != null){ n.s.update(); n = n.next; } } public String toString(){ String toReturn = “”; Node n = end; while (n != null){ toReturn = toReturn + n.s; //toReturn = n.s + “ ” + toReturn; //to print order added n = n.next; } return toReturn; } public static void main(String[] args){ SphereHolder d = new SphereHolder(); d.append(new Sphere()); d.append(new Sphere()); d.append(new Sphere()); d.pop(); } Recall: public void append(Sphere toAppend){ Node toAdd = new Node(toAppend); toAdd.next = end; end = toAdd; } Local Scope append pop toAdd Node 3121 4487 2122 d SphereHolder 1299 Memory Addr: 1299 end: Node 3121 4487 2122 null Addr: 3121 num: 1 next: null Addr: 4487 num: 2 next: 3121 Addr: 2122 num: 3 next: 4487 null Node s1 Node s2 Node s3 Node s4 Node s6 Node s5 For ints: class Node{ int num; Node next; public Node(int num){ this.num = num; } } (The everything is basically the same) null Node num = 3 Node num = 1 Node num = 4 Node num = 1 Node num = 9 Node num = 5