04 Arrays
January 6, 2024 · 4 min read
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!
One-Dimensional Arrays #
Defining Arrays #
Array definitions are similar to variable definitions.
public class Main {
public static void main(String[] args) {
int[] a;// Definition: define an array a
a = new int[10]; // Initialization: initialize a as an array of length 10, meaning a contains 10 int variables; equivalent to =>int[] a = new int[10]// Define and initialize at the same time
int[] a = new int[10], b;
float[] f = new float[33];
double[] d = new double[123];
char[] c = new char[21];
// Arrays can be defined for more than just primitive data types; String arrays can also be defined
String[] strs = new String[10];// This array contains 10 String variables
}
}
Initializing Arrays #
(1) Default initialization:
int[] a = new int[3]; // An array with 3 elements, all with the value 0.
In Java, the default initial value is 0, converted to the appropriate zero value for each type (in C++, local variable arrays have indeterminate values by default).
- An array of
intvalues is initialized to 0 by default - An array of
stringvalues has a default value of null - An array of
charvalues yields 0 using the UTF-8 character set - An array of
doublevalues has a default value of 0.0 - An array of
floatvalues has a default value of 0.0 - An array of
booleanvalues has a default value of false
int[] b; // b is also an array; without initialization it is an empty array.
[]denotes an array type. In Java, writing[]before the name puts the array type up front, so everything defined afterward is an array; here b has no specified length, so it is 0. (In C++, you must write something likeint b[10].)
(2) Direct initialization:
- Java does not have the concept of pointers
- In Java, an array cannot be used without initialization (defining it without initializing it is not enough); it is an empty array, null. It must be assigned a value before use. Variables are the same: they cannot be used without an initial value, so Java is less prone to errors.
public class Main {
public static void main(String[] args) {
int[] a = {0, 1, 2}; // An array with 3 elements: 0, 1, 2
a = new int[10];// Arrays can be reassigned in Java; they are variables, just like ordinary variables.
int[] b = new int[3]; // An array with 3 elements, all with the value 0
char[] d = {'a', 'b', 'c'}; // Initialize a character array
}
}
Accessing Array Elements #
Access arrays by index.
int[] f = new int[n+1];In Java, an array length can be a variable, whereas in C++ it is preferable to use a constant.
public class Main {
public static void main(String[] args) {
int[] a = {0, 1, 2}; // Array indices start at 0
System.out.printf("%d %d %d\n", a[0], a[1], a[2]);
a[0] = 5;
System.out.println(a[0]);
}
}
Multidimensional Arrays #
A multidimensional array is an array of arrays: its elements are themselves arrays.
Defining Multidimensional Arrays #
int[][] a = new int[3][4]; // An array of size 3, each element an array of 4 integers.
int[][][] b = new int[10][20][30]; // An array of size 10; each element is an array of 20 arrays, each containing 30 integers
Initializing Multidimensional Arrays #
For (data type variable name: array name)
{
// This variable name represents each element of the array; use it directly to operate on the element
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// The dimensions of a two-dimensional array can have different lengths, though they are usually the same.
int[][] a = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11},
};
for (int[] row: a) { // Iterate over the range
for (int x: row) // Iterate over the range
System.out.printf("%d ", x);
System.out.println();
}
}
}
Accessing Multidimensional Arrays #
a[i][j]; // Element j of row i
Property length: returns the length of an array; do not add parentheses (this is not an API).
a.length; // Return the length of array a
a[i].length; // If a is a two-dimensional array, return the length of each inner array
Common APIs #
To use Arrays, add import java.util.Arrays
- Property
length: returns the length of an array; do not add parentheses Arrays.sort(): sorts an arrayArrays.fill(int[] a, int val): fills an array; it can only initialize a one-dimensional array, not a multidimensional array.Arrays.Fill (q, -1).Arrays.toString(): converts an array into a string showing its elementsArrays.deepToString(): converts a multidimensional array into a string showing its elements- Arrays cannot change length
Arrays.sort(q) #
Sort the elements of array q from smallest to largest. To sort from largest to smallest, use an anonymous function (similar to a Python lambda expression), and define the array using an object type.
One-dimensional arrays:
Integer[] q= new Integer[n]; // Integer is an object type for integers
Arrays.sort(q, (x,y) ->{ // Add an anonymous function (comparison function)
// To add a comparison function, the type must be an object type
return x-y; // x-y sorts ascending; y-x sorts descending
// A negative x-y means x goes before y; a positive value means x goes after y
// A positive y-x (x<y) means x goes after y
} )
Two-dimensional arrays: Each one-dimensional array in a two-dimensional array is itself an object, so Integer is not needed.
Arrays.sort(q, (x,y) ->{ // Add an anonymous function
return x[0]-y[0];
} )
Related readings
If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: