Java 中的基本陣列
在 Java 中,任何物件或基元型別都可以是陣列。通過 arrayName [index]訪問陣列指示,例如 myArray[0]
。陣列中的值是通過 myArray [0] = value 設定的,例如,如果 myArray 是 String [] myArray[0] = "test";
型別的陣列
public class CreateBasicArray{
public static void main(String[] args){
// Creates a new array of Strings, with a length of 1
String[] myStringArray = new String[1];
// Sets the value at the first index of myStringArray to "Hello World!"
myStringArray[0] = "Hello World!";
// Prints out the value at the first index of myStringArray,
// in this case "Hello World!"
System.out.println(myStringArray[0]);
// Creates a new array of ints, with a length of 1
int[] myIntArray = new int[1];
// Sets the value at the first index of myIntArray to 1
myIntArray[0] = 1;
// Prints out the value at the first index of myIntArray,
// in this case 1
System.out.println(myIntArray[0]);
// Creates a new array of Objects with a length of 1
Object[] myObjectArray = new Object[1];
// Constructs a new Java Object, and sets the value at the first
// index of myObjectArray to the new Object.
myObjectArray[0] = new Object();
}
}