Arrays: fixed-size lists
Until now each variable held a single value. What do you do if you need the grades of thirty students or the temperature of each day of the month? Creating thirty variables is not reasonable. An array is a collection of values of the same type, stored next to each other in memory and reachable by a numeric position. It is the most basic data structure in Java and the base on which more comfortable ones are built.
Creating and accessing
There are two ways to create an array. With new you give the type and the size, and every position starts with the default value (0 for numbers, false for boolean, null for objects). With a literal list between braces you give the values directly. Positions are called indexes and start at 0; the last index is length - 1. Careful: length is an attribute of the array and is written without parentheses, unlike the length() method of String. The size cannot change once created.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] grades = new int[5]; // five zeros
grades[0] = 8;
grades[1] = 6;
grades[4] = 10;
System.out.println(Arrays.toString(grades)); // [8, 6, 0, 0, 10]
String[] days = {"Mon", "Tue", "Wed"}; // literal
System.out.println(days.length); // 3 (no parentheses)
System.out.println(days[days.length - 1]); // Wed: the last one
double[] prices = {9.5, 3.25, 7.0};
double total = 0;
for (int i = 0; i < prices.length; i++) {
total += prices[i];
}
System.out.println("Total: " + total); // 19.75
// for-each: read every element, no index needed
for (String day : days) {
System.out.print(day + " ");
}
System.out.println();
// Arrays are objects: assignment copies the reference, not the data
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
System.out.println(a[0]); // 99
int[] c = Arrays.copyOf(a, a.length); // a real copy
c[0] = 1;
System.out.println(a[0] + " " + c[0]); // 99 1
}
}Classic mistakes
The most frequent mistake is accessing a position that does not exist. If the array has 5 elements and you write grades[5], Java throws ArrayIndexOutOfBoundsException while running. That is why in loops we use i < array.length and not <=. The other big mistake is believing that b = a copies the content: it only copies the reference, so both variables point to the same array, as you saw in the previous example. To really copy use Arrays.copyOf or clone().
Walking, finding the maximum and matrices
A very common pattern is to walk through the array keeping the best value seen so far: you start with the first element and, in each round, replace it if you find a greater one. The java.util.Arrays class provides utilities: toString to print, sort to order, fill to fill and equals to compare contents. There are also two-dimensional arrays, that is, arrays of arrays, which represent tables or boards: matrix[row][column].
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] values = {14, 3, 27, 9, 21};
int max = values[0];
int min = values[0];
int sum = 0;
for (int v : values) {
if (v > max) max = v;
if (v < min) min = v;
sum += v;
}
System.out.println("max=" + max + " min=" + min); // max=27 min=3
System.out.println("average=" + (double) sum / values.length); // 14.8
Arrays.sort(values);
System.out.println(Arrays.toString(values)); // [3, 9, 14, 21, 27]
// Two-dimensional array: 2 rows, 3 columns
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // 6
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
try {
System.out.println(values[5]); // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage()); // Index 5 out of bounds for length 5
}
}
}- An array of objects (for example String[]) starts full of null; calling a method on an unassigned element throws NullPointerException.
- You cannot enlarge an array: if you need more room, you create a bigger one and copy the data, or you use ArrayList, which we will see in the next lesson.
- Comparing two arrays with == or with the array's own equals() only compares references; use Arrays.equals(a, b).
- Printing an array with System.out.println(array) shows something like [I@1b6d3586, not the content; use Arrays.toString.
Проверьте себя
Вопрос 1 из 1In an array of 5 elements, which index is the last?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов