09 ArraysAndLists
09 ArraysAndLists
Q1
Syntax: ElementType[] name
Examples:
◦ A variable: double[] averages;
Q2
Reading:
◦ double exp = polls[42] * elecVotes[42];
Writing:
◦ elecVotes[37] = 11;
Q5,6
Type parameter can’t be a primitive type
◦ Not: ArrayList<int> runs;
◦ But: ArrayList<Integer> runs;
Q7
Auto-boxing: automatically enclosing a
primitive type in a wrapper object when
needed
Example:
◦ You write: Integer m = 6;
◦ Java does: Integer m = new Integer(6);
Example:
◦ ArrayList<Integer> runs =
new ArrayList<Integer>();
runs.add(9); // 9 is auto-boxed
◦ int r = runs.get(0); // result is unboxed
Old school
double scores[] = …
double sum = 0.0;
for (int i=0; i < scores.length; i++) {
sum += scores[i];
}
New, whiz-bang, enhanced for loop
double scores[] = …
double sum = 0.0; No index
for (double sc : scores) { variable
sum += sc; Gives a name
} (sc here) to
Say ―in‖ each element
ArrayList<State> states = …
int total = 0;
for (State st : states) {
total += st.getElectoralVotes();
}
Q8
Finish ElectionSimulator