How do I declare and initialize an array in Java?

2018-12-30 23:35发布

How do I declare and initialize an array in Java?

21条回答
与风俱净
2楼-- · 2018-12-31 00:26

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.

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.

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 00:27

Another way to declare and initialize ArrayList:

private List<String> list = new ArrayList<String>(){{
    add("e1");
    add("e2");
}};
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 00:31

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).

查看更多
登录 后发表回答