Implementing ArrayList Algorithms

Help Questions

AP Computer Science A › Implementing ArrayList Algorithms

Questions 1 - 2
1

Using the given problem statement, which line of code correctly initializes the ArrayList for this problem?

ArrayList scores = new ArrayList[];

ArrayList scores = new ArrayList(10, 0);

ArrayList scores = new ArrayList();

ArrayList scores = new ArrayList<>();

Explanation

This question tests AP Computer Science A skills, specifically using ArrayLists to implement and analyze algorithms. ArrayLists in Java provide dynamic sizing and random access capabilities, making them suitable for various algorithmic problems requiring flexible data storage and manipulation. In this scenario, the task requires correctly initializing an ArrayList to store Integer objects, which involves understanding Java's syntax for generics and the distinction between primitive types and wrapper classes. Choice B is correct because it uses the proper generic syntax ArrayList for the wrapper class (not the primitive int), and employs the diamond operator <> on the right side, which is the modern Java syntax for type inference. Choice A is incorrect because ArrayList cannot directly store primitive types like int; it requires the Integer wrapper class to store numeric values. To help students: Explain the difference between primitive types and wrapper classes in the context of collections. Practice writing ArrayList declarations for different data types and emphasize modern Java syntax conventions.

2

Based on the scenario above, which line correctly initializes an ArrayList to store daily temperatures as integers?

ArrayList temps = new ArrayList();

ArrayList temps = new ArrayList();

int[] temps = new ArrayList();

ArrayList temps = new ArrayList();

Explanation

This question tests AP Computer Science A skills, specifically using ArrayLists to implement and analyze algorithms. ArrayLists in Java provide dynamic sizing and random access capabilities, making them suitable for various algorithmic problems requiring flexible data storage and manipulation. In this scenario, the task involves correctly initializing an ArrayList to store integer values, which requires understanding Java's type system and generics. Choice B is correct because ArrayLists cannot store primitive types directly, so we must use the wrapper class Integer instead of int, and proper generic syntax requires specifying the type in angle brackets. Choice A is incorrect because ArrayList is invalid syntax - Java generics require reference types, not primitives like int. To help students: Explain the difference between primitive types and their wrapper classes. Emphasize that collections in Java can only store objects, not primitives, necessitating autoboxing.