COMP1010 Week 9
Administrative Announcements and Assessment Guidelines
Academic Calendar and Recess:
- Week of COMP1010 marks the return from the teaching recess.
- The teaching recess constitutes a break in formal teaching activities rather than an assessment holiday.
Skills Lab Scheduling and Relocation:
- General inquiries regarding the Skills Lab are addressed within the pinned "Skills Lab FAQ" announcement.
- A frequent student query concerns inability to attend registered laboratory classes (e.g., attending a Friday session instead).
- Course instructors lack administrative authority to reallocate students between registered timetable classes.
Major Assignment Specifications:
- Submission deadline: Week on Thursday.
- Assignment specifications originally mentioned recursive data structures because in prior iterations of the curriculum, recursive data structures were taught earlier, and the assignment was due around Week or Week .
- Because the current scheduling places the assignment due date before recursive data structures have been fully taught, recursive data structures are strictly not required in the major assignment submission.
- Students who have already implemented recursive data structures will not be penalized or marked down; that specific component will simply not be assessed.
- Eligible students may apply for a standard short extension through the student portal.
Skills Lab Memory Diagram Feedback and Retake Policy:
- All memory diagram questions from the first attempt have been graded, and marks have been updated in student totals.
- Due to schedule constraints, formal review sessions could not occur between attempts; however, to review sessions are scheduled to allow students to inspect their memory diagram grading and request adjustments if grading discrepancies exist.
- A dedicated practice project (rather than a quiz) has been released containing graduated difficulty tiers: Pass level, Credit level, Distinction level, and High Distinction level.
- The second attempt is entirely optional: students satisfied with their first attempt mark (e.g., receiving out of ) are under no obligation to sit the Week second attempt, though any student retains the right to retake the exam to increase their mark (e.g., from to ).
Foundations: Concept Dependencies and Expression Evaluation
Interconnected Nature of Programming Concepts:
- Difficulties encountered in advanced programming topics often stem not from the target topic itself, but from cumulative knowledge gaps in prerequisite fundamentals.
- Failure in modular assessments (such as writing functions) typically traces back to unaddressed misunderstandings in variable types, operators, conditionals, or iterative loops studied in prerequisite units such as COMP1000.
- Automated feedback platforms such as CodeRunner and CodingBat serve to identify and bridge these latent conceptual gaps.
Integer Division and Implicit Upcasting:
- Consider the task of defining a function that accepts an integer parameter and returns half its value as a double-precision floating-point number.
- Expected input-output mappings:
- Input Output
- Input Output
- Input Output
- Common naive implementation:
return n / 2;- Failure mechanism:
- This code does not trigger a compiler type error; it generates a logical error.
- The variable is of type
int(). - The literal is also of type
int(as opposed to ). - Evaluating an expression of the form performs integer truncation, returning an
intresult (e.g., evaluates to the integer ). - In Java, returning an
intfrom a method with adoublereturn type is syntactically valid due to automatic widening (upcasting), converting to and to . - Conversely, returning a
doublewhen anintis expected is illegal without explicit narrowing. - Rectifying the logical error:
- Explicitly cast the operand to double:
return (double) n / 2; - Alternatively, divide by a double literal:
return n / 2.0; - In both approaches, the expression evaluates as or , producing an accurate double expression.
Composition and Object Memory Models
Java Identifier Constraints:
- Package names in Java cannot begin with a numeric digit (e.g., naming a package starting with a digit causes a compilation syntax error).
Recap of Class Composition:
- Composition represents a "has-a" relationship where an outer class encapsulates instances or references of other classes.
- The
Pointclass represents a 2D coordinate: - Instance variables:
int x,int y. - Parameterized constructor: copies incoming arguments to internal fields.
toString()method: formats output as(x, y)(e.g.,(2, 5)or(1, 7)).- The
Lineclass represents a line segment connecting two points: - Instance variables:
Point start,Point end. - Constructor: takes two
Pointobjects and performs reference copies intostartandend. toString()method: concatenates text withstartandend, which automatically invokes thePoint.toString()method implicitly on both references.
References vs. Instances in Memory Diagrams:
- Instance: A heap-allocated memory block containing the actual instance variables defined by the class, created via the
newkeyword. In memory diagrams, instances have incoming arrows. - Reference: An identifier or variable that stores the memory address of an instance. In memory diagrams, references have outgoing arrows.
- Object sizing: The physical memory allocated to an instance is determined directly by the number and primitive data types of its declared instance variables.
- Structural rules for reference arrows:
- A reference can point to at most one instance (a single reference having multiple outgoing arrows to distinct instances is invalid).
- Multiple references can point to the identical instance (multiple incoming arrows to a single instance is valid and common).
- Independent object graphs can coexist without cross-references.
- Credit-level memory analysis for line composition (
Line line = new Line(p1, p2);): - Point references:
p1,p2,line.start,line.end( references). - Line references:
line( reference). - Total references: references ( outgoing arrows).
- Total instances:
Lineinstance andPointinstances ( instances with incoming arrows). - Online visualization tooling is transitioning from Python Tutor to
from0.dev.
- Instance: A heap-allocated memory block containing the actual instance variables defined by the class, created via the
Conceptual Introduction to Recursive Data Structures
Pedagogical Progression in Computing:
- Direct workplace usage of raw manual linked nodes is rare; however, they form the foundational stepping stone for advanced computer science architectures:
- Graph structures underpin social networking algorithms, artificial intelligence models, cloud platforms, and large-scale recommendation systems.
- Understanding graphs requires mastery of trees, which in turn requires mastery of linked lists.
Defining "Recursive" in Object Composition:
- A class is recursive if it contains an instance variable that references an object of the same class type.
- Example: A
Personclass modeling genealogical data: - Attributes:
String name,Date dateOfBirth, derivedage. - Parent relationships: Mother and father are themselves of type
Person. - Erroneous colloquial definition: An instance of
Personcontains two otherPersonobjects inside itself. - Precise computer science definition: An instance of
Personholds references to two otherPersoninstances.
Anatomy of a Node:
- Payload: The substantive information being stored. While introductory examples use
int data, a payload can consist of strings, medical records, match configurations, or arbitrary complex objects. - Pointer / Link: A reference attribute conventionally declared as
Node next, pointing to another node of the exact same type.
- Payload: The substantive information being stored. While introductory examples use
Physical Memory Architecture: Arrays vs. Linked Lists:
- Primitive memory sizing in Java:
byte:short:int:double:boolean: individually, though arrays of booleans employ specialized bit-packing.- Array Memory Requirements:
- Arrays require contiguous blocks of system memory.
- An array of integers requires of uninterrupted contiguous space.
- An array of integers requires (approximately ) of contiguous memory.
- Historical and Economic Context of Hardware RAM:
- Memory previously cost approximately .
- Historic lows reached around the 2023–2024 timeframe.
- Recent supply demands from AI data centers and cloud computing have driven semiconductor and memory prices up by to .
- Linked List Architectural Trade-offs:
- Physical classroom demonstration: Three students seated side-by-side represent an array (one contiguous block). Dispersed students (Owen, Jonathan, and Isaac) represent a linked list, where Owen holds Jonathan's address, and Jonathan holds Isaac's address.
- Advantage: Linked lists eliminate the requirement for large, contiguous memory blocks; memory allocations can occur in small fragments dispersed throughout the heap.
- Disadvantage (Overhead): A linked list consumes substantially more aggregate memory than an array because each payload requires an accompanying memory address pointer (reference). Storing items introduces additional link references.
- Disadvantage (Performance): Non-contiguous access makes traversing a linked list noticeably slower than sequential array indexing.
The Node Class Architecture and Manual Chaining
- Standard Node Class Implementation:
- Declared with fields for data and pointer:
public class Node {
public int data;
public Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public String toString() {
return data + " ";
}
}
- Manual Chaining Mechanism:
- Creating four disconnected nodes, each with a null next reference:
Node a = new Node(10, null);
Node b = new Node(70, null);
Node c = new Node(20, null);
Node d = new Node(90, null);
- Chaining using reference assignment:
a.next = b; // a.next becomes a reference copy of b
b.next = c; // b.next becomes a reference copy of c
c.next = d; // c.next becomes a reference copy of d
- Severing Direct Reference Handles:
- Setting external reference variables to null:
b = null;
c = null;
d = null;
- The data values , , and are not deallocated by the garbage collector because an active reference chain remains rooted at variable
a. - Accessing sequential elements through explicit pointer navigation:
- First node:
aevaluates to instance holding payload . - Second node:
a.nextevaluates to instance holding payload . - Third node:
a.next.nextevaluates to instance holding payload . - Fourth node:
a.next.next.nextevaluates to instance holding payload . - End of list:
a.next.next.next.nextevaluates tonull.
- First node:
- Attempting attribute access on
null(e.g.,a.next.next.next.next.next) throws a runtimeNullPointerException.
Linked List Traversal and Pointer Preservation
- Iterative Traversal Pattern:
- Hardcoding chained
.nextcalls is unprogrammatic and unscalable for dynamically sized collections. - Just as an accumulator loop iterates across an integer sequence (, , incrementing via until reaching ), list traversal advances an object pointer:
- Hardcoding chained
Node current = a;
while (current != null) {
System.out.print(current);
current = current.next;
}
Mechanics of the Assignment Statement
current = current.next:- The assignment operator evaluates its right-hand side first.
- The expression
current.nextresolves to the memory address stored in thenextattribute of the current instance. - The resulting reference is then written back into the left-hand variable
current, advancing the pointer to the succeeding instance. - When
currentreaches the terminalnullreference, the conditioncurrent != nullevaluates tofalse, gracefully terminating the loop.
The Critical Rule of Pointer Preservation:
- The external handle referencing the beginning of the list (
head) must never be used directly as the loop counter. - Executing
while (head != null) { head = head.next; }causesheadto evaluate tonullupon loop completion. - Advancing
headdirectly destroys access to the start of the list, rendering subsequent traversals impossible. - Always initialize a temporary cursor (
temporcurrent) to preserve the anchorhead.
- The external handle referencing the beginning of the list (
List Construction via Prepending (Head Insertion):
- Generating a random linked list by inserting nodes at the beginning:
Node head = null;
for (int i = 0; i < 5; i++) {
int payload = (int)(Math.random() * 100) + 1; // Random integer in [1, 100]
head = new Node(payload, head);
}
- Because each new node sets its
nextpointer to the currentheadand subsequently becomes the newhead, the insertion process inverts the generation sequence. - Example: Generating values in chronological order produces a final linked list ordered as:
Iterative and Recursive Algorithms on Linked Lists
- Algorithm 1: Aggregating Payloads (Total Sum):
- Accumulates all integer values across a list:
int total = 0;
Node temp = head;
while (temp != null) {
total += temp.data; // Extract payload
temp = temp.next; // Reallocate cursor
}
A list of random values spanning sums to approximately , yielding an average of roughly , conforming to expected probabilistic distributions.
- Algorithm 2: Selective Aggregation (Summing Odd Numbers):
Sums only odd payloads using modular arithmetic:
int totalOdd = 0;
Node temp = head;
while (temp != null) {
if (temp.data % 2 != 0) { // Handles both positive (1) and negative (-1) odd remainders
totalOdd += temp.data;
}
temp = temp.next;
}
Checking
temp.data % 2 != 0is necessary because negative odd integers yield under the modulo operator, failing a strict== 1check.- Algorithm 3: Modular Functional Traversal (Count Even Numbers):
Encapsulates list counting logic in a static helper method:
public static int countEven(Node start) {
int result = 0;
while (start != null) {
if (start.data % 2 == 0) {
result++;
}
start = start.next; // Mutating 'start' does not alter caller's 'head'
}
return result;
}
Scope and Reference Passing in Java: When passing
headintocountEven(head), the method parameterstartreceives a copy of the reference address. Reassigningstart = start.nextinside the function does not modify the originalheadvariable in the calling function, eliminating the need to construct a secondary temporary variable.- Algorithm 4: Iterative Key Search (Contains Method):
Linearly searches for a specific key value within the list:
public static boolean contains(Node start, int key) {
while (start != null) {
if (start.data == key) {
return true; // Key found
}
start = start.next;
}
return false; // Loop terminated without finding key
}
In a randomly populated list of items where each item is between and , the probability of containing the value is exactly .
- Algorithm 5: Recursive Search Implementation:
Expresses linear list traversal as a pure recursive decomposition without iterative loops:
public static boolean containsRecursive(Node start, int key) {
// Base Case 1: Empty list cannot contain any value
if (start == null) {
return false;
}
// Base Case 2: Current node matches target key
if (start.data == key) {
return true;
}
// Recursive Step: Check the remainder of the list
return containsRecursive(start.next, key);
}
- Metaphorical demonstration: Searching for a student named Anthony along a queue of students. If the first student is not Anthony, apply the identical verification algorithm to the remaining sub-queue starting at the next student.
Questions & Discussion
Lab Class Attendance Discrepancies:
- Question: Can a student who cannot attend their officially scheduled Skills Lab session attend an alternate session (e.g., Friday) instead?
- Answer: No. Instructors lack administrative permissions to transfer or reallocate students across timetable classes. Students must adhere to the policies detailed in the pinned Skills Lab FAQ announcement.
Short Extension System Behavior:
- Question: Has anyone encountered submission failures or technical bugs when applying for the short extension via the system?
- Answer: Students confirmed that applications processed smoothly without operational issues, confirming the process functions properly.
Skills Lab Optional Retake Eligibility:
- Question: If a student completed the first Skills Lab attempt and is satisfied with their mark, do they have to sit the second attempt during Week ?
- Answer: No. If a student scored high (e.g., out of ) and is satisfied, they do not need to attend the second attempt. However, any student wishing to increase their grade to is fully entitled to take the second attempt.
Linked Memory Storage Equivalence:
- Question: Does a linked list take the same amount of physical memory as an array to store a set of students?
- Answer: No. While the baseline payload data takes the same storage, linked structures require extra memory overhead to store the explicit reference addresses linking each node to its neighbor, whereas arrays store items contiguously without per-element address pointers.
Functional Parameter Mutability:
- Question: Does advancing
start = start.nextinside a helper method destroy the caller's reference to the list? - Answer: No. Java passes object references by value. The parameter
startholds a reference copy ofhead. Mutatingstartmodifies only the local pointer within the method frame; the caller'sheadvariable remains unaffected.
- Question: Does advancing