Constructing Programs That Apply Arrays and Lists
Arrays
Fixed-size, ordered collections of elements of the same data type.
One-Dimensional Arrays (1D)
Represent a single row or list of elements.
Python:
numbers = [1, 2, 3, 4]Java:
int[] numbers = {1, 2, 3, 4};Two-Dimensional Arrays (2D)
Represent rows and columns (like a table).
Python:
matrix = [[1, 2], [3, 4]]Java:
int[][] matrix = { {1, 2}, {3, 4} };Use arrays when size is known and constant.
Trying to resize → arrays are fixed-size.
Lists (Dynamic Structures)
Ordered, resizable collections of elements.
Python Lists:
fruits = ["apple", "banana"]
fruits.append("cherry") # add
fruits.remove("banana") # remove
for f in fruits: # traverse
print(f)Java ArrayLists:
import java.util.ArrayList;
ArrayList<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("banana");
fruits.remove("banana");
for (String f : fruits) {
System.out.println(f);
}Lists are best when data size changes.
Confusing Python lists (dynamic arrays) with Java arrays (static).
Core Operations on Arrays and Lists
- Add Elements
- Array: Must specify index or create a new array.
- List: Use .append() (Python) / .add() (Java).
- Remove Elements
- Array: Manual shift needed.
- List: .remove() handles it.
- Traverse Elements
Python:
for item in my_list:
print(item)Java:
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}Use loops for traversal.
Off-by-one errors when looping through arrays.
Comparison: Arrays vs. Lists
| Feature | Arrays (static) | Lists (dynamic) |
|---|---|---|
| Size | Fixed | Resizable |
| Memory usage | Efficient | Extra overload |
| Access speed | Fast( 0(1) ) | Fast ( 0(1) ) |
| Insert/delete | Slow (requires shifting) | Fast (automatic) |
| Examples | Java arrays, NumPy arrays | Python lists, Java ArrayLists |
Be ready to:
- Write code for 1D and 2D arrays.
- Demonstrate adding, removing, traversing a list.
- Compare static (arrays) vs. dynamic (lists/ArrayLists).