CS 1110/1111: Introduction to Programming

Lecture 19

Announcements

Slides from 1pm and 3pm

Talking Points

You can have the type of thing stored in an array be an array.

int[] x = new int[12]; // 12 integers, all 0
int[][] y = new int[][10]; // space for 10 arrays of integers (all null right now)
y[0] = x; // the first array in x is the same as the y array
y[1] = new int[5]; // the second array in y is a new array of 5 integers
String[][] s = {{"a", "b"}, {"hi", "bye"}, {"I", "like", "most", "food"}};
System.out.println(s[0]); // nonsense; arrays don't print well
System.out.println(s[0][1]); // b
System.out.println(s[1][0]); // hi
System.out.println(s.length); // 3
System.out.println(s[0].length); // 2
System.out.println(s[2].length); // 4
double[][] twoD = new double[3][4]; // an array of 3 arrays, each having 4 doubles inside
System.out.println(twoD[0]); // nonsense; arrays don't print well
System.out.println(twoD[0][1]); // 0.0
twoD[0][1] = 3.14;
twoD[1] = new double[6];

Images are usually thought of as 2D arrays (pixels).


There is a class ArrayList that is a nicer-to-use kind of list.

ArrayArrayListComments
int[] x; ArrayList<Integer> y; ArrayLists can't store primitives, hence Integer vs int.
x = new int[5]; y = new ArrayList<Integer>(); ArrayLists always start empty. Arrays always have to be given a size when created.
x[3] = 2; y.set(3, 2); 3 has to be a valid index; otherwise throws an IndexOutOfBoundsException
int z = x[0]; int z = y.get(0); 0 has to be a valid index; otherwise throws an IndexOutOfBoundsException
int w = x.length; int w = y.size();
impossible y.add(4); Puts 4 at the end of the list, making the list one longer.
impossible y.add(2, 4); Puts 4 into index 2, pushing what used to be there and everything after than back and making the list one longer.
impossible y.remove(3); Removes the value at index 3, making the list one shorter.
impossible y.remove(new Integer(3)); Removes the first value 3 from the list, making the list one shorter; does nothing if no 3s are in the list.
x = {1, 2, 3}; lots of .add() calls
write a loop System.out.println(y);
write a loop boolean has = y.contains(3); True if there's a 3 in the list.
write a loop int idx = y.indexOf(3); The index of the first 3 in the list, or −1 if there is no 3 in the list.

ArrayList is just one type of List object, all of which are used in very similar ways. You'll learn about why there are many and what the others are in CS 2110.

ArrayList will make the StudentRatio problem in HW4 much easier than it would be without them.

Copyright © 2014 by Luther Tychonievich. All rights reserved.