Overview
An array is a container object that holds a fixed number of values of a single type. The length of an array is fixed once it is created. Jave has special language support for arrays: declarations, initialization, and indexing. As arrays are objects, whatever we pass an array to a method or use an array variable, we are making a copy of the array reference, not a copy of an array.
Array entries can be any of type. The declarations and initialization of arrays are actually to allocate memory space for arrays and assign initial values to each element. Once the initialization is completed, the length of the array cannot be changed later. You can access the element of the array or put values in the array by numberical index (using a[i], i is the indices of the array a, starting at 0). length is used to obtain the length of the array (a.length).
Creating and initializing
There are three distinct steps to make an array in Java.
- Declare the array name and type
- Create the array
- Initialize the array values
// long form
double[] a; // declaration
a = new double[10]; // array creation
/*
* if this step isn't given, java will initialize it.
*/
for(int i = 0; i < 10; i++) a[i] = 0.0; // value initialization
Here is an example to create array and access elements of it.
public class ArrayDemo {
public static void main(String[] args) {
// (1) Dynamic initialization with new operator
String[] aArr = new String[10];
aArr[0] = "hello";
aArr[1] = "world";
for(int i = 0; i < aArr.length; i++) {
System.out.println(aArr[i]);
}
// (2) Static initializaiton (aggregate initialization)
int[] iArr = {101, 102, 103, 104};
for(int i = 0; i < iArr.length; i++) {
System.out.println(iArr[i]);
}
// Get the length of array
System.out.println(aArr.length);
System.out.println(iArr.length);
}
}
/* output:
hello
world
null
null
null
null
null
null
null
null
101
102
103
104
10
4
*/
From the results above, we can get that for the array without initial values, Java will give the initial value null. Actually, Java will give each array initial values if we don't do it. Here is the rules:
- For the array of int, short, long and byte types, the initial values will be 0.
- For the array of float and double types, the initial values will be 0.0.
- For the array of char type, the initial values will be 'u0000'.
- For the array of boolean type, the initial values will be false.
- For the array of reference type (class, interface and array), the initial values will be null.
Aliasing
Note carefully that an array name refers to the whole array. If the array name is assigned to another, then both refer to the same array.
int[] a = new int[5];
a[2] = 100;
int[] b = a;
b[2] = 50; // a[2] is now 50.
How does the Array store in memory?
Arrays are first-class objects. Regardless of what type of array you’re working with, the array identifier is actually a reference to a true object that’s created on the heap. Let's use a diagram to illustrate this.
char[] a = new char[3];
a[0] = 'x';
a[1] = 'y';
a[2] = 'z';
stack heap +-----+ +------+------+------+ | a |-------------->| a[0] | a[1] | a[2] | // the array object +-----+ +------+------+------+ V V V +---+ +---+ +---+ |'x'| |'y'| |'z'| +---+ +---+ +---+ So a and a[i] are actually reference variables.
Nested Arrays
Personally, I don't think multiple-dimensional array is a good name for nested arrays. I think nested arrays more reflect the real situation. To create nested arrays, you need to add one or more pair of square brackets. Nest once, add a pair of square brackets. Nest N times, add N pairs of square brackets.
String[][] s = new String[2][3];
+-------+ |s[0][0]| +-------+ | ... | +-------+ | ... | +-------+ +-----+ | +-----+ |s[0] |------------/ | s |-->+-----+ +-----+ |s[1] |------------\ +-----+ | +-------+ |s[1][0]| +-------+ | ... | +-------+ | ... | +-------+ s[0] and s[1] are the elements of the array s, s[0] points a array object whose size is 3 we defined in creating the array. The array object is called nested array. The same situation exists in s[1].
Array Processing Examples
- create an array with random values [1].
- print the array values, one per line [2].
- find the maxiumum of the array values [3].
- calculate the average of the array values [4].
- copy to another array [5].
- reverse the elements within an array [6].
[1] |
double[] a = new double[10];
for (int i = 0; i < 10; i++) a[i] = Math.random();
[2] |
for (int i = 0; i < 10; i++) System.out.println(a[i]);
[3] |
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < 10; i++) {
if (a[i] > max) max = a[i];
}
[4] |
double sum = 0.0;
for (int i = 0; i < 10; i++) {
sum += a[i];
}
double ave = sum / 10;
[5] |
double[] b = new double[10];
for (int i = 0; i < 10; i++) {
b[i] = a[i];
}
[6] |
for (int i = 0; i < N/2; i++) {
double tmp = a[i];
a[i] = a[N-1-i];
a[N-1-i] = tmp;
}
Arrays in depth
Methods for Arrays
Arrays have many methods that you can use in Java. Here lists some methods frequently used.
1. Print arrays
String[] strArr = {"abc", "xyz", "baz"};
String s = Arrays.toString(strArr);
/*
* Directly print the reference value,
* actually, it's memory address value.
*/
System.out.println(strArr); //[Ljava.lang.String;@3d0bbf6d
System.out.println(s); // [abc, xyz, baz]
2. Check if an array contains a certain value.
- use list
- use set
- use a loop
String[] sArr = {"xyz", "bar", "baz", "abc"};
// use list
boolean bList = Arrays.asList(sArr).contains("bar");
// use set
boolean bSet = new HashSet<String>(Arrays.asList(sArr)).contains("bar");
System.out.println(bList);
System.out.println(bSet);
/*
* Output:
* true
* true
*/
// use a loop
public static boolean containsValue(String[] sArr, String tarStr) {
for (String e: sArr) {
if (e.equals(tarStr)) return true;
}
return false;
}
3. Concatenate two arrays
String[] sArr1 = {"bar", "xyz", "baz"};
String[] sArr2 = {"foo", "chr"};
// apache commons lang org.apache.commons.lang3.ArrayUtils
String[] sArrCon = ArrayUtils.addAll(sArr1, sArr2);
System.out.println(Arrays.toString(sArrCon)); // [bar, xyz, baz, foo, chr]
4. Reverse an array
We can use the method ArrayUtils.reverse() from apache commons lang3, but how to implement it if we don't have apache commons lang3.
char[] cArr = {'a', 'b', 'c'};
ArrayUtils.reverse(cArr);
System.out.println(Arrays.toString(cArr));
Here implements a static reverse method for char type Arrays. For other types, you can use the same method in which you just replace char type using other types.
public static void reverse(char[] array) {
if(array == null) return;
int N = array.length;
for(int i = 0; i < N/2; i++) {
char tmp = array[i];
array[i] = array[N - 1 - i];
array[N - 1 -i] = tmp;
}
}