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

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

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

21个解决方案

2299 votes

您可以使用数组声明或数组文字(但只有在声明并立即影响变量时,才能使用数组文字重新分配数组)。

对于原始类型:

int[] myIntArray = new int[3];

int[] myIntArray = {1,2,3};

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

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

String[] myStringArray = new String[3];

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

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

当您首先声明数组然后初始化它时,第三种初始化方法很有用。 演员是必要的。

String[] myStringArray;

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

glmxndr answered 2018-11-28T22:35:30Z

234 votes

有两种类型的数组。

一维数组

默认值的语法:

int[] num = new int[5];

或者(不太喜欢)

int num[] = new int[5];

给定值的语法(变量/字段初始化):

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

或者(不太喜欢)

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

注意:为了方便int [] num更可取,因为它清楚地告诉你这里是关于数组的。 否则没什么区别。 一点也不。

多维数组

宣言

int[][] num = new int[5][2];

要么

int num[][] = new int[5][2];

要么

int[] num[] = new int[5][2];

初始化

num[0][0]=1;

num[0][1]=2;

num[1][0]=1;

num[1][1]=2;

num[2][0]=1;

num[2][1]=2;

num[3][0]=1;

num[3][1]=2;

num[4][0]=1;

num[4][1]=2;

要么

int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

衣衫褴褛的阵列(或非矩形阵列)

int[][] num = new int[5][];

num[0] = new int[1];

num[1] = new int[5];

num[2] = new int[2];

num[3] = new int[3];

所以我们在这里明确定义列。

其他方式:

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

用于访问:

for (int i=0; i

for (int j=0;j

System.out.println(num[i][j]);

}

或者:

for (int[] a : num) {

for (int i : a) {

System.out.println(i);

}

}

粗糙的数组是多维数组。

有关解释,请参阅官方java教程中的多维数组详细信息

Isabella Engineer answered 2018-11-28T22:36:55Z

117 votes

Type[] variableName = new Type[capacity];

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

Type variableName[] = new Type[capacity];

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

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

Nate answered 2018-11-28T22:37:15Z

32 votes

您可以通过多种方式在Java中声明数组:

float floatArray[]; // Initialize later

int[] integerArray = new int[10];

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

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

Anirudh answered 2018-11-28T22:37:39Z

26 votes

我发现如果您理解每个部分会很有帮助:

Type[] name = new Type[5];

Type[]是名为name的变量的类型(“name”称为标识符)。 文字“Type”是基本类型,括号表示这是该基数的数组类型。 数组类型依次是它们自己的类型,它允许您创建多维数组,如Type[][](Type []的数组类型)。 关键字new表示要为新阵列分配内存。 括号之间的数字表示新数组的大小和分配的内存量。 例如,如果Java知道基类型Type需要32个字节,并且您需要大小为5的数组,则需要在内部分配32 * 5 = 160个字节。

您还可以使用已存在的值创建数组,例如

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

它不仅会创建空白空间,还会使用这些值填充它。 Java可以告诉基元是整数,并且它们中有5个,因此可以隐式确定数组的大小。

Chet answered 2018-11-28T22:38:13Z

26 votes

以下显示了数组的声明,但未初始化该数组:

int[] myIntArray = new int[3];

以下显示了数组的声明和初始化:

int[] myIntArray = {1,2,3};

现在,以下还显示了数组的声明和初始化:

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

但是第三个显示了匿名数组对象创建的属性,它由引用变量“myIntArray”指向,所以如果我们只写“new int [] {1,2,3};” 那么这就是如何创建匿名数组对象。

如果我们只写:

int[] myIntArray;

这不是数组的声明,但以下语句使上述声明完成:

myIntArray=new int[3];

Amit Bhandari answered 2018-11-28T22:38:55Z

23 votes

或者,

// Either method works

String arrayName[] = new String[10];

String[] arrayName = new String[10];

这声明了一个名为arrayName的数组,大小为10(你可以使用0到9的元素)。

Thomas Owens answered 2018-11-28T22:39:20Z

22 votes

此外,如果您想要更动态的东西,还有List接口。 这不会表现得那么好,但更灵活:

List listOfString = new ArrayList();

listOfString.add("foo");

listOfString.add("bar");

String value = listOfString.get(0);

assertEquals( value, "foo" );

Dave answered 2018-11-28T22:39:40Z

12 votes

制作数组有两种主要方法:

这个,对于一个空数组:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array

而这一个,对于一个初始化的数组:

int[] array = {1,2,3,4 ...};

您还可以创建多维数组,如下所示:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions

int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

codecubed answered 2018-11-28T22:40:13Z

9 votes

以原始类型int[][]为例。 有几种方法可以声明和int[]数组:

int[] i = new int[capacity];

int[] i = new int[] {value1, value2, value3, etc};

int[] i = {value1, value2, value3, etc};

在所有这些中,您可以使用int[][]而不是int[]。

使用反射,您可以使用int[][]

注意,在方法参数中,int[][]表示int[].基本上,任何数量的参数都可以。 使用代码更容易解释:

public static void varargs(int fixed1, String fixed2, int... varargs) {...}

...

varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}

varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};

在方法内部,int[][]被视为正常int[]. int[][]只能在方法参数中使用,因此int[x][y]将无法编译。

请注意,将int[][]传递给方法(或任何其他int[])时,不能使用第三种方法。 在语句int[][]中,编译器假定int[x][y]表示i[x-1][y-1].但这是因为您声明了一个变量。 将数组传递给方法时,声明必须为int[3][5]或new Type[] {...}。

多维数组

多维数组很难处理。 本质上,2D数组是一个数组数组。 int[][]表示数组int[]s。 关键是如果int[][]声明为int[x][y],则最大索引为i[x-1][y-1]。实际上,矩形int[3][5]是:

[0, 0] [1, 0] [2, 0]

[0, 1] [1, 1] [2, 1]

[0, 2] [1, 2] [2, 2]

[0, 3] [1, 3] [2, 3]

[0, 4] [1, 4] [2, 4]

HyperNeutrino answered 2018-11-28T22:41:04Z

8 votes

如果你想使用反射创建数组,那么你可以这样做:

int size = 3;

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

Muhammad Suleman answered 2018-11-28T22:41:25Z

7 votes

声明一个对象引用数组:

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

}

}

ravi answered 2018-11-28T22:41:45Z

6 votes

数组是项目的顺序列表

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =

{

{ value, value, value, .. value },

{ value, value, value, .. value },

.. .. .. ..

{ value, value, value, .. value }

};

如果它是一个对象,那么它就是相同的概念

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =

{

{ new Object(), new Object(), .. new Object() },

{ new Object(), new Object(), .. new Object() },

.. .. ..

{ new Object(), new Object(), .. new Object() }

};

如果是对象,则需要将其分配给M以使用M对其进行初始化,类别如N和N^M是特殊情况,将按以下方式处理

String [] a = { "hello", "world" };

// is equivalent to

String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };

// is equivalent to

Integer [] b = { new Integer(1234), new Integer(5678) };

通常,您可以创建M维度的数组

int [][]..[] array =

// ^ M times [] brackets

{{..{

// ^ M times { bracket

// this is array[0][0]..[0]

// ^ M times [0]

}}..}

// ^ M times } bracket

;

值得注意的是,创建一个M维度阵列在空间方面是昂贵的。 因为当您在所有维度上创建M维度数组N时,数组的总大小大于N^M,因为每个数组都有一个引用,并且在M维度上有一个(M-1)维数组 参考文献。 总大小如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0

// ^ ^ array reference

// ^ actual data

Khaled.K answered 2018-11-28T22:42:23Z

5 votes

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

public ArrayList arrayName;

arrayName = new ArrayList();

为数组赋值:

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

从数组中读取:

ClassName variableName = arrayName.get(index);

注意:

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

for循环:

//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 (int i = 0; i < arrayName.size(); i++){

//manipulate array here

}

Samuel Newport answered 2018-11-28T22:43:05Z

5 votes

在Java 8中,您可以像这样使用。

String[] strs = IntStream.range(0, 15) // 15 is the size

.mapToObj(i -> Integer.toString(i))

.toArray(String[]::new);

Chamly Idunil answered 2018-11-28T22:43:25Z

5 votes

在Java 9中

使用不同的IntStream.takeWhile和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"};

Oleksandr answered 2018-11-28T22:43:57Z

3 votes

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

Kirill Podlivaev answered 2018-11-28T22:44:35Z

1 votes

声明和初始化ArrayList的另一种方法:

private List list = new ArrayList(){{

add("e1");

add("e2");

}};

Clement.Xu answered 2018-11-28T22:44:55Z

0 votes

使用局部变量类型推断,您只需指定一次类型:

var values = new int[] { 1, 2, 3 };

要么

int[] values = { 1, 2, 3 }

Konstantin Spirin answered 2018-11-28T22:45:15Z

0 votes

你也可以用java.util.Arrays这个:

List number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]

这个非常简单明了。我没有在其他答案中,所以我想我可以添加它。

Sylhare answered 2018-11-28T22:45:40Z

-6 votes

int[] SingleDimensionalArray = new int[2]

int[][] MultiDimensionalArray = new int[3][4]

TreyMcGowan answered 2018-11-28T22:45:55Z

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值