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
With local variable type inference you only have to specify type once:
or
Declare and initialize for Java 8 and later. Create a simple integer array:
Create a random array for integers between [-50, 50] and for doubles [0, 1E17]:
Power-of-two sequence:
For String[] you must specify a constructor:
Multidimensional arrays:
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:
For classes, for example
String
, it's the same:The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.
There are various ways in which you can declare an array in Java:
You can find more information in the Sun tutorial site and the JavaDoc.
If you want to create arrays using reflections then you can do like this:
For creating arrays of class Objects you can use the
java.util.ArrayList
. to define an array:Assign values to the array:
Read from the array:
Note:
variableName
is a reference to the array meaning that manipulatingvariableName
will manipulatearrayName
for loops:
for loop that allows you to edit
arrayName
(conventional for loop):