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


当前回答

为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]]

其他回答

在Java8中,您可以使用类似的功能。

String[] strs = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> Integer.toString(i))
    .toArray(String[]::new);

声明数组:int[]arr;

初始化数组:int[]arr=new int[10];10表示数组中允许的元素数

声明多维数组:int[][]arr;

初始化多维数组:int[][]arr=new int[10][17];10行17列和170个元素,因为10乘以17等于170。

初始化数组意味着指定数组的大小。

有时我用它来初始化字符串数组:

private static final String[] PROPS = "lastStart,storetime,tstore".split(",");

它以更昂贵的初始化为代价,减少了报价混乱。

声明和初始化数组非常容易。例如,您希望在数组中保存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”执行此操作时,您不必手动输入值。

Type[] variableName = new Type[capacity];

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



Type variableName[] = new Type[capacity]; 

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

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