如何在Java中声明和初始化数组?


当前回答

int[] x = new int[enter the size of array here];

例子:

int[] x = new int[10];
              

Or

int[] x = {enter the elements of array here];

例子:

int[] x = {10, 65, 40, 5, 48, 31};

其他回答

要创建类对象的数组,可以使用java.util.ArrayList.来定义数组:

public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();

为数组赋值:

arrayName.add(new ClassName(class parameters go here);

从阵列中读取:

ClassName variableName = arrayName.get(index);

注:

variableName是对数组的引用,这意味着操纵variableName将操纵arrayName

对于循环:

//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName

for循环,允许您编辑arrayName(常规for循环):

for (int i = 0; i < arrayName.size(); i++){
    //manipulate array here
}
int[] x = new int[enter the size of array here];

例子:

int[] x = new int[10];
              

Or

int[] x = {enter the elements of array here];

例子:

int[] x = {10, 65, 40, 5, 48, 31};
Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};

也是有效的,但我更喜欢在类型后面加括号,因为更容易看出变量的类型实际上是一个数组。

在Java 9中

使用不同的IntStream.iterate和IntStream.takeWhile方法:

int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();

Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]


int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();

Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

在Java 10中

使用局部变量类型推断:

var letters = new String[]{"A", "B", "C"};

声明对象引用数组:

class Animal {}

class Horse extends Animal {
    public static void main(String[] args) {

        /*
         * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
         */
        Animal[] a1 = new Animal[10];
        a1[0] = new Animal();
        a1[1] = new Horse();

        /*
         * Array of Animal can hold Animal and Horse and all subtype of Horse
         */
        Animal[] a2 = new Horse[10];
        a2[0] = new Animal();
        a2[1] = new Horse();

        /*
         * Array of Horse can hold only Horse and its subtype (if any) and not
           allowed supertype of Horse nor other subtype of Animal.
         */
        Horse[] h1 = new Horse[10];
        h1[0] = new Animal(); // Not allowed
        h1[1] = new Horse();

        /*
         * This can not be declared.
         */
        Horse[] h2 = new Animal[10]; // Not allowed
    }
}