2017
07-16

# Array数组

Name

Array数组

Examples

int[] numbers = new int;

numbers = 90; // Assign value to first element in the array

numbers = 150; // Assign value to second element in the array

numbers = 30; // Assign value to third element in the array

int a = numbers + numbers; // Sets variable ‘a’ to 240

int b = numbers + numbers; // Sets variable ‘b’ to 180 int[] numbers = { 90, 150, 30 }; // Alternate syntax

int a = numbers + numbers; // Sets variable ‘a’ to 240

int b = numbers + numbers; // Sets variable ‘b’ to 180 int degrees = 360;

float[] cos_vals = new float[degrees];

// Use a for() loop to quickly iterate

// through all values in an array.

for (int i=0; i < degrees; i++) {

cos_vals[i] = cos(TWO_PI/degrees * i);

} float[] randoms = new float;

for (int i = 0; i < randoms.length; i++) {

randoms[i] = random(100);

}

// You can also use an enhanced loop

// to access the elements of an array

for (float val : randoms) {

println(val);

}

// This works with arrays of objects, too,

// but not when first making the array

PVector[] vectors = new PVector;

for (int i = 0; i < vectors.length; i++) {

vectors[i] = new PVector();

}

// The syntax only applies when iterating

// over an existing array

for (PVector v : vectors) {

point(v.x, v.y);

}

Description

An array is a list of data. It is possible to have an array of any type of data. Each piece of data in an array is identified by an index number representing its position in the array. The first element in the array is , the second element is , and so on. Arrays are similar to objects, so they must be created with the keyword new.

Each array has a variable length, which is an integer value for the total number of elements in the array. Note that since index numbering begins at zero (not 1), the last value in an array with a lengthof 5 should be referenced as array (that is, the length minus 1), not array, which would trigger an error.

Another common source of confusion is the difference between using length to get the size of an array and length() to get the size of a String. Notice the presence of parentheses when working with Strings. (array.length is a variable, while String.length() is a method specific to the String class.)

Syntax

datatype[] var

var[element] = value

var.length

Parameters

 Datatype 数据类型 any primitive or compound datatype, including user-defined classes 任何基元或复合数据类型, 包括用户定义的类 var any valid variable name 任何有效的变量名 Element 元素 int: must not exceed the length of the array minus 1 不能超过数组的长度减去1 Value 值 data to assign to the array element; must be the same datatype as the array 要分配给数组元素的数据;必须与数组的数据类型相同 