Lecture 3: References, Recursion, and Lists

8/31/2020

Primitive Types

Variables in Java

Walrus a = new Walrus(1000, 8.3); Walrus b; b = a; b.weight = 5; System.out.println(a); System.out.println(b); Result: 5 5
int x = 5; int y; y = x; x = 2; System.out.println(x); System.out.println(y); Result: 2 5

Bits

Declaring a Variable (simplified)

int x; double y; x = -1431195969; y = 567213.112

Simplified Box Notation

The Golden Rule of Equals (GRoE)

Reference Types

Reference Types

Class Instantiations

public class Walrus { public int weight; public double tuskSize; public Walrus(int w, double ts) { weight = w; tuskSize = ts; } }

Reference Type Variable Declarations

Reference Types Obey the Golden Rule of Equals

Parameter Passing

The Golden Rule of Equals (and Parameter Passing)

public static double average(double a, double b) { return (a + b) / 2; } public static void main(String[] args) { double x = 5.5; double y = 10.5; double avg = average(x, y); }

The Golden Rule: Summary

Instantiation of Arrays

Declaration and Instantiation of Arrays

Assignment of Arrays

IntList and Linked Data Structures

IntList

public class IntList { public int first; public IntList rest; public IntList(int f, IntList r) { first = f; rest = r; } public static void main(String[] args) { IntList L = new IntList(15, null); L = new IntList(10, L); L = new IntList(5, L); } }

IntList

public class IntList { public int first; public IntList rest; public IntList(int f, IntList r) { first = f; rest = r; } public int size() { // Return the size of the list using... recursion! if (rest == null) { return 1; } return 1 + this.rest.size(); } public int iterativeSize() { // Return the size of the list using no recursion IntList p = this; int totalSize = 0; while (p != null) { totalSize += 1; p = p.rest; } return totalSize; } public static void main(String[] args) { IntList L = new IntList(15, null); L = new IntList(10, L); L = new IntList(5, L); } }

Challenge

public class IntList { public int first; public IntList rest; public IntList(int f, IntList r) { first = f; rest = r; } public int size() { // Return the size of the list using... recursion! if (rest == null) { return 1; } return 1 + this.rest.size(); } public int iterativeSize() { // Return the size of the list using no recursion IntList p = this; int totalSize = 0; while (p != null) { totalSize += 1; p = p.rest; } return totalSize; } public int get(int i) { // Returns the ith item of this IntList if (i == 0) { return first; } return rest.get(i - 1); } public static void main(String[] args) { IntList L = new IntList(15, null); L = new IntList(10, L); L = new IntList(5, L); } }