Array is the most basic data structure that accesses values of the same type using consecutive indices. Once the size is set, it cannot be changed (fixed size), but it is fast and memory efficient.
Learning Objectives
- Declare, initialize, and access one-dimensional and two-dimensional arrays
- Traverse with
forand enhanced for - Use utilities such as
Arrays.toString/sort/copyOf - Know the difference between
int[](primitive) andInteger[](object)
Key concepts
1) One-dimensional array
int[] nums = new int[5]; // {0,0,0,0,0}
nums[0] = 10;
String[] colors = {"red", "green", "blue"};
System.out.println(colors.length); // 3
length is a field, not a method (no parentheses).
2) 2-dimensional array
int[][] mat = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(mat[1][2]); // 6
System.out.println(mat.length); //2 (row)
System.out.println(mat[0].length); //3 (column)
A two-dimensional array in Java is an array of arrays. Each row may have a different length (jagged array).
3) Arrays utility
import java.util.Arrays;
int[] a = {3, 1, 4, 1, 5, 9, 2};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
int[] copy = Arrays.copyOf(a, 5);
4) Primitive array vs object array
int[] xs = new int[3]; //Default 0
Integer[] ys = new Integer[3]; //default null
int[] is fast and has small memory, but it cannot be directly added to the collection (List<Integer>).
See as example
Example 1 — Array1D.java: One-dimensional array basics
public class Array1D {
public static void main(String[] args) {
int[] nums = new int[5];
for (int i = 0; i < nums.length; i++) nums[i] = (i + 1) * 10;
for (int n : nums) System.out.print(n + " ");
System.out.println();
System.out.println("length=" + nums.length);
}
}
Execution result
10 20 30 40 50
length=5
Memo: The index starts from 0. If out of range, ArrayIndexOutOfBoundsException.
Example 2 — Array2D.java: Two-dimensional array
public class Array2D {
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3},
{4, 5, 6}
};
for (int r = 0; r < mat.length; r++) {
for (int c = 0; c < mat[r].length; c++) {
System.out.print(mat[r][c] + " ");
}
System.out.println();
}
}
}
Execution result
1 2 3
4 5 6
Memo: Access is in the order of row index → column index.
Example 3 — ArraysUtil.java: Sort·Copy·toString
import java.util.Arrays;
public class ArraysUtil {
public static void main(String[] args) {
int[] a = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
int[] head = Arrays.copyOf(a, 4);
System.out.println(Arrays.toString(head));
int[] slice = Arrays.copyOfRange(a, 2, 6);
System.out.println(Arrays.toString(slice));
}
}
Execution result
[1, 1, 2, 3, 4, 5, 6, 9]
[1, 1, 2, 3]
[2, 3, 4, 5]
Note: to of copyOfRange(from, to) is exclusive.
Example 4 — IntVsInteger.java: primitive vs boxing
import java.util.Arrays;
import java.util.List;
public class IntVsInteger {
public static void main(String[] args) {
int[] xs = new int[3]; //Default 0
Integer[] ys = new Integer[3]; //default null
System.out.println("xs[0]=" + xs[0]);
System.out.println("ys[0]=" + ys[0]);
Integer[] zs = {1, 2, 3};
List<Integer> list = Arrays.asList(zs);
System.out.println(list);
}
}
Execution result
xs[0]=0
ys[0]=null
[1, 2, 3]
Note: Arrays.asList returns a fixed size List (except when calling .add).
Common Mistakes
- Call parentheses like
nums.length()→ length is a field ArrayIndexOutOfBoundsExceptionout of index range- Assume that the row lengths of the two-dimensional array are the same (can be jagged)
- Trap where
Arrays.asList(int[])becomesList<int[]>(IntStreamis used in primitive array) - Use
==for array comparison (useArrays.equalsorArrays.deepEquals)
Cleanup
- Arrays are fast, fixed-size data structures.
- Index is 0..length-1
- Most utilities are gathered as static methods in the
Arraysclass. - If you need a mutable collection,
List(next section)
Try it yourself
cd 03_collection_generic/11_array/src
javac ArraysUtil.java
java ArraysUtil