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


当前回答

如果要使用反射创建阵列,可以执行以下操作:

 int size = 3;
 int[] intArray = (int[]) Array.newInstance(int.class, size ); 

其他回答

有多种方法可以在Java中声明数组:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};

您可以在Sun教程网站和JavaDoc中找到更多信息。

公告

一维阵列

int[] nums1; // best practice
int []nums2;
int nums3[];

多维数组

int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];

声明和初始化

一维阵列

使用默认值

int[] nums = new int[3]; // [0, 0, 0]

Object[] objects = new Object[3]; // [null, null, null]

带数组文字

int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};

Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};

带有循环

int[] nums = new int[3];
for (int i = 0; i < nums.length; i++) {
    nums[i] = i; // can contain any YOUR filling strategy
}

Object[] objects = new Object[3];
for (int i = 0; i < objects.length; i++) {
    objects[i] = new Object(); // can contain any YOUR filling strategy
}

带循环for和Random

int[] nums = new int[10];
Random random = new Random();
for (int i = 0; i < nums.length; i++) {
    nums[i] = random.nextInt(10); // random int from 0 to 9
}

使用流(从Java 8开始)

int[] nums1 = IntStream.range(0, 3)
                       .toArray(); // [0, 1, 2]
int[] nums2 = IntStream.rangeClosed(0, 3)
                       .toArray(); // [0, 1, 2, 3]
int[] nums3 = IntStream.of(10, 11, 12, 13)
                       .toArray(); // [10, 11, 12, 13]
int[] nums4 = IntStream.of(12, 11, 13, 10)
                       .sorted()
                       .toArray(); // [10, 11, 12, 13]
int[] nums5 = IntStream.iterate(0, x -> x <= 3, x -> x + 1)
                       .toArray(); // [0, 1, 2, 3]
int[] nums6 = IntStream.iterate(0, x -> x + 1)
                       .takeWhile(x -> x < 3)
                       .toArray(); // [0, 1, 2]

int size = 3;
Object[] objects1 = IntStream.range(0, size)
        .mapToObj(i -> new Object()) // can contain any YOUR filling strategy
        .toArray(Object[]::new);

Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy
        .limit(size)
        .toArray(Object[]::new);

使用Random和Stream(从Java 8开始)

int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();

多维数组

使用默认值

int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]

带数组文字

int[][] nums1 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
int[][] nums2 = new int[][]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

Object[][] objects1 = {
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};

带有循环

int[][] nums = new int[3][3];
for (int i = 0; i < nums.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        nums[i][j] = i + j; // can contain any YOUR filling strategy
    }
}

Object[][] objects = new Object[3][3];
for (int i = 0; i < objects.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        objects[i][j] = new Object(); // can contain any YOUR filling strategy
    }
}

为Java 8和更高版本声明和初始化。创建一个简单的整数数组:

int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

为[-50,50]之间的整数和双[0,1E17]创建随机数组:

int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();

两个序列的功率:

double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]

对于String[],必须指定构造函数:

String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));

多维数组:

String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
    .toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]

您可以使用数组声明或数组文字(但仅当您立即声明并影响变量时,数组文字不能用于重新分配数组)。

对于基本类型:

int[] myIntArray = new int[3]; // each element of the array is initialised to 0
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};

// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html

int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort 

对于类,例如String,它是相同的:

String[] myStringArray = new String[3]; // each element is initialised to null
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};

当您首先声明一个数组,然后初始化它,将一个数组作为函数参数传递,或者返回一个数组时,第三种初始化方法非常有用。需要显式类型。

String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};

声明和初始化数组非常容易。例如,您希望在数组中保存5个整数元素,即1、2、3、4和5。您可以通过以下方式进行操作:

a)

int[] a = new int[5];

or

b)

int[] a = {1, 2, 3, 4, 5};

因此基本模式用于初始化,方法a)的声明是:

datatype[] arrayname = new datatype[requiredarraysize];

数据类型应为小写。

因此,基本模式用于初始化,方法a的声明是:

如果是字符串数组:

String[] a = {"as", "asd", "ssd"};

如果是字符数组:

char[] a = {'a', 's', 'w'};

对于浮点双精度,数组的格式将与整数相同。

例如:

double[] a = {1.2, 1.3, 12.3};

但是当您通过“方法a”声明和初始化数组时,您必须手动或通过循环或其他方式输入值。

但是,当您通过“方法b”执行此操作时,您不必手动输入值。