Goals and Examples
Practice and hence solidify your understanding of using arrays and ArrayLists:
- Declaring an array or ArrayList. Examples:
double[] data;
Employee[] employees;
ArrayList scores;
ArrayList students;
- Allocating space for an array or ArrayList. Examples (assuming declarations above):
data = new double[50];
employees = new Employee[this.numberOfEmployees];
scores = new ArrayList();
students = new ArrayList();
// You also can declare and allocate space in a single statement:
double[] moreData = new double[100];
ArrayList moreStudents = new ArrayList();
- Getting (accessing) elements in an array or ArrayList.
Examples (assuming declarations above, and also see examples to the right):
... data[4] ...
... employees[k] ...
... scores.get(4) ...
... students.get(k) ...
- Setting (mutating) elements in an array or ArrayList.
Examples (assuming declarations above, and also see examples to the right):
data[4] = valueFromFile;
employees[k] = new Employee(...);
scores.set(4, scoreFromFile);
students.set(k, new Student(...)) ...
// Also can add elements to the end of an ArrayList, and more:
students.add(new Student(...));
students.remove(j); // Remove element at index j,
// shifting the elements behind it
You can see more examples of arrays and ArrayLists in the
slides on arrays and ArrayLists.
|
More examples
- Initializing all elements of an array or ArrayList, using old-style loops:
Dog[] dogs = new Dog[numberOfDogs];
for (int k = 0; k < dogs.length; ++k) {
dogs[k] = new Dog(...);
}
ArrayList cats = new ArrayList();
for (int k = 0; k < numberOfCats; ++k) {
cats.add(new Cat(...));
}
- Counting array or ArrayList elements that satisfy a given property,
using old-style loops:
int count = 0;
for (int k = 0; k < dogs.length; ++k) {
if (... dogs[k] ...) {
++ count;
}
}
int otherCount = 0;
for (int k = 0; k < cats.length; ++k) {
if (... cats.get(k) ...) {
++ otherCount;
}
}
- Summing array or ArrayList elements,
using NEW-style loops:
double totalWeight = 0;
for (Dog dog : dogs) {
totalWeight += dog.weight();
}
int totalAge = 0;
for (Cat cat : cats) {
totalAge += cat.age();
}
Note: you can NOT use the enhanced for loop to modify an element of an array or ArrayList.
- The “histogram loop pattern”:
- Declare an array or ArrayList that will hold histogram values 0 .. n,
where events are numbered and n is the biggest event that can occur.
- Initialize all elements of the histogram to 0.
- Repeatedly:
- Get one event (call it m) from which the histogram is to be built.
- Increment the histogram count at index m.
The array or ArrayList now holds the desired histogram.
|