How do I declare and initialize an array in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I find it is helpful if you understand each part:
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 likeType[][]
(the array type of Type[]). The keywordnew
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 typeType
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
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.
Another way to declare and initialize ArrayList:
Alternatively,
That declares an array called
arrayName
of size 10 (you have elements 0 through 9 to use).