Defination

int[] a;  // It does not yet initialize a with an actual array.
int[] a = new int[100];
var a = new int[100];
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
  • array of numbers, initialized with zero
  • array of boolean, initialized with false
  • array of objects, initialized with special value null

Arrays in Java vs. so in C++

int[] a = new int[100];  // Java
// not
int a[100];  // C++
// but
int* a = new int[100];  // C++

In Java, the [] operator is predefined to perform bounds checking. Furthermore, there is no pointer arithmetic—you can’t increment a to point to the next element in the array.

you can assign to an array, but …

smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };  // new produce an 无名array
// is shorthand for
int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;

You can copy one array variable into another, but then both variables refer to the same array

if you really want to copy an array, use method: copyOf:

int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);

an array of length 0

new elementType[0];
new elementType[] {};

Note that an array of length 0 is not the same as null.

Multidimensional Arrays

定义经典new一个或者花括号一个

由于 “array of arrays”

int[][] odds = new int[NMAX + 1][];  // allocate rows
for (int n = 0; n <= NMAX; n++)  // allocate each col
	odds[n] = new int[n + 1];

Multi Arrays in Java vs. so in C++

double[][] balances = new double[10][6];  // Java
// not
double balances[10][6];  // C++
// also not
double (*balances)[6] = new double[10][6];  // C++
// but
double** balances = new double*[10];  // C++
for (i = 0; i < 10; i++)
	balances[i] = new double[6];

Mercifully, this loop is automatic when you ask for a new double[10][6]. When you want ragged arrays, you allocate the row arrays separately.

Member(?)

for (int i = 0; i < a.length; i++)  // here *a.length*
	System.out.println(a[i]);
 
System.out.println(Arrays.toString(a));
 
Arrays.sort(a)