简体   繁体   English

如何用常量声明一个int数组?

[英]How to declare an int array with a constant?

I'm a really basic beginner at Java and I've been trying to figure out how to declare arrays. 我是Java的真正基础入门者,并且一直在尝试弄清楚如何声明数组。 If I want to use a constant int SIZE that is set equal to 5, would it be any different from declaring a regular array? 如果我想使用设置为5的int SIZE常量,与声明常规数组有什么不同吗?

From what I've learned, this is one way to declare an array: 据我了解,这是声明数组的一种方法:

int intArray[] = new int[3];

And this would give an array from 1 to 3, I think... 我想这将得到一个从1到3的数组。

In Java, you declare constants by using the final keyword: 在Java中,您可以使用final关键字声明常量:

final int SIZE = 5;

then, you can use this constant to initialize your array: 然后,您可以使用此常量来初始化数组:

int intArray[] = new int[SIZE];

Note: 注意:

  • Indices in most programming languages start with 0 . 大多数编程语言中的索引均以0开头。 So, to access the elements of the array, you will have to use indices starting from 0 : 因此,要访问数组的元素,您将必须使用从0开始的索引:

     intArray[0] -> first element intArray[1] -> second element intArray[2] -> third element 

Edit: 编辑:

  • If you tried to access to the array using intArray[SIZE] , you will get an IndexOutOfBoundsException because you can only access with indices between 0 and SIZE - 1 . 如果您尝试使用intArray[SIZE]访问该数组,则会得到IndexOutOfBoundsException因为您只能使用0SIZE - 1之间的索引进行访问。 Note that in this range there are SIZE numbers of elements. 请注意,在此范围内有SIZE个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM