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

[英]How do I declare and initialize an array in Java?


How do I declare and initialize an array in Java?

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

19 个解决方案

#1


2141  

You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

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

For primitive types:

基本类型:

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

For classes, for example String, it's the same:

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

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

The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.

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

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

#2


218  

There are two types of array.

有两种类型的数组。

One Dimensional Array

Syntax for default values:

语法的默认值:

int[] num = new int[5];

Or (less preferred)

或(首选)

int num[] = new int[5];

Syntax with values given (variable/field initialization):

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

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

Or (less preferred)

或(首选)

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

Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.

注意:为了方便起见,[]num更可取,因为它清楚地说明了您在这里讨论的是数组。否则没有区别。不客气。

Multidimensional array

Declaration

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

Or

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

Or

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

Initialization

 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;

Or

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

Ragged Array (or Non-rectangular Array)

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

So here we are defining columns explicitly.
Another Way:

这里我们明确地定义列。另一种方法:

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

For Accessing:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}

Alternatively:

另外:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}

Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials

不规则数组是多维数组。有关解释,请参阅官方java教程中的多维数组细节

#3


115  

Type[] variableName = new Type[capacity];

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



Type variableName[] = new Type[capacity]; 

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

is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.

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

#4


32  

There are various ways in which you can declare an array in Java:

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

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

You can find more information in the Sun tutorial site and the JavaDoc.

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

#5


26  

The following shows the declaration of an array, but the array is not initialized:

下面显示了一个数组的声明,但是数组没有初始化:

 int[] myIntArray = new int[3];

The following shows the declaration as well as initialization of the array:

如下所示为数组的声明和初始化:

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

Now, the following also shows the declaration as well as initialization of the array:

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

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

But this third one shows the property of anonymous array-object creation which is pointed by a reference variable "myIntArray", so if we write just "new int[]{1,2,3};" then this is how anonymous array-object can be created.

但是这第三个图展示了匿名arrayobject创建的属性,该属性由一个引用变量“myIntArray”指向,因此,如果我们只写“new int[]{1,2,3}”,那么就可以创建匿名的arrayobject。

If we just write:

如果我们只写:

int[] myIntArray;

this is not declaration of array, but the following statement makes the above declaration complete:

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

myIntArray=new int[3];

#6


25  

I find it is helpful if you understand each part:

我觉得如果你能理解每个部分是很有帮助的:

Type[] name = new Type[5];

Type[] is the type of the variable called name ("name" is called the identifier). The literal "Type" is the base type, and the brackets mean this is the array type of that base. Array types are in turn types of their own, which allows you to make multidimensional arrays like Type[][] (the array type of Type[]). The keyword new says to allocate memory for the new array. The number between the bracket says how large the new array will be and how much memory to allocate. For instance, if Java knows that the base type Type takes 32 bytes, and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.

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

You can also create arrays with the values already there, such as

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

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

which not only creates the empty space but fills it with those values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.

它不仅创建了空空间,而且还填充了这些值。Java可以判断原语是整数,并且有5个,因此可以隐式地确定数组的大小。

#7


22  

Alternatively,

另外,

// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];

That declares an array called arrayName of size 10 (you have elements 0 through 9 to use).

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

#8


22  

Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:

此外,如果您想要更动态的东西,可以使用列表接口。这将不会表现得很好,但更灵活:

List<String> listOfString = new ArrayList<String>();

listOfString.add("foo");
listOfString.add("bar");

String value = listOfString.get(0);
assertEquals( value, "foo" );

#9


12  

There are two main ways to make an array:

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

This one, for an empty array:

这个,对于一个空数组:

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

And this one, for an initialized array:

这个初始化数组

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

You can also make multidimensional arrays, like this:

你也可以制作多维数组,像这样:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

#10


9  

Take the primitive type int for example. There are several ways to declare and int array:

以原始类型int为例。声明和int数组有几种方式:

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

where in all of these, you can use int i[] instead of int[] i.

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

With reflection, you can use (Type[]) Array.newInstance(Type.class, capacity);

通过反射,您可以使用(Type[]) Array.newInstance(类型)。类、容量);

Note that in method parameters, ... indicates variable arguments. Essentially, any number of parameters is fine. It's easier to explain with code:

注意,在方法参数中,…显示变量参数。本质上,任何数量的参数都可以。用代码更容易解释:

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};

Inside the method, varargs is treated as a normal int[]. Type... can only be used in method parameters, so int... i = new int[] {} will not compile.

在方法内部,varargs被视为一个普通的int[]。类型……只能在方法参数中使用,所以int…i = new int[]{}不会编译。

Note that when passing an int[] to a method (or any other Type[]), you cannot use the third way. In the statement int[] i = *{a, b, c, d, etc}*, the compiler assumes that the {...} means an int[]. But that is because you are declaring a variable. When passing an array to a method, the declaration must either be new Type[capacity] or new Type[] {...}.

注意,在将int[]传递给方法(或任何其他类型[])时,不能使用第三种方法。在语句int[] i = *{a, b, c, d,等}*中,编译器假设{…}意味着int[]。但那是因为你在声明一个变量。当向方法传递数组时,声明必须是新类型[容量]或新类型[]{…}。

Multidimensional Arrays

Multidimensional arrays are much harder to deal with. Essentially, a 2D array is an array of arrays. int[][] means an array of int[]s. The key is that if an int[][] is declared as int[x][y], the maximum index is i[x-1][y-1]. Essentially, a rectangular int[3][5] is:

多维数组更难处理。从本质上说,二维数组是数组的数组。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]

#11


7  

If you want to create arrays using reflections then you can do like this:

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

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

#12


7  

Declaring an array of object references:

声明对象引用数组:

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
    }
}

#13


6  

Array is a sequential list of items

数组是项的顺序列表

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 }
};

If it's an object, then it's the same concept

如果它是一个物体,那么它就是同一个概念

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() }
};

In case of objects, you need to either assign it to null to initialize them using new Type(..), classes like String and Integer are special cases that will be handled as following

在对象的情况下,您需要将其赋值为null以使用new Type(..)来初始化它们,类的类如String和Integer是特殊的情况,将被处理如下。

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) };

In general you can create arrays that's M dimensional

一般来说,你可以创建一个M维的数组。

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

It's worthy to note that creating an M dimensional array is expensive in terms of Space. Since when you create an M dimensional array with N on all the dimensions, The total size of the array is bigger than N^M, since each array has a reference, and at the M-dimension there is an (M-1)-dimensional array of references. The total size is as following

值得注意的是,创建一个M维数组在空间上是非常昂贵的。因为当你创建一个M和N维数组的所有维度,数组的总大小大于N ^ M,因为每个数组的引用,M-dimension(M - 1维数组的引用。总大小如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data

#14


5  

For creating arrays of class Objects you can use the java.util.ArrayList. to define an array:

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

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

Assign values to the array:

为数组赋值:

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

Read from the array:

读取数组:

ClassName variableName = arrayName.get(index);

Note:

注意:

variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName

variableName是对数组的引用,这意味着操纵变量名将操作arrayName。

for loops:

for循环:

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

for loop that allows you to edit arrayName (conventional for loop):

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

for (int i = 0; i < arrayName.size(); i++){
    //manipulate array here
}

#15


3  

Declare and initialize for Java 8 and later. Create a simple integer array:

声明并初始化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]

Create a random array for integers between [-50, 50] and for doubles [0, 1E17]:

在[- 50,50]和double [0,1e17]之间创建一个随机数组。

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

Power-of-two sequence:

2的幂,序列:

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]

For String[] you must specify a constructor:

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

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

Multidimensional arrays:

多维数组:

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

#16


3  

In Java 8 you can use like this.

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

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

#17


1  

Another way to declare and initialize ArrayList:

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

private List<String> list = new ArrayList<String>(){{
    add("e1");
    add("e2");
}};

#18


0  

In Java 9

Using the IntStream.iterate(...) methods:

使用IntStream.iterate(…)方法:

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]

#19


-4  

int[] SingleDimensionalArray = new int[2]

int[][] MultiDimensionalArray = new int[3][4]
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2009/07/29/232b5b924c453e9dbfa4291fc5537357.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告