arrays数组入门


备注

数组是大多数编程语言提供的构造,用于通过索引访问一组相同的对象。在某些语言中,类型必须相同(Java),而在其他语言中(JavaScript,Python),多个类型可以在数组中。

可用性

大多数编程语言都提供了数组,通常使用square [] 或round () 括号来访问元素,例如Carray[6]VBarray(6)

Java中的基本数组

在Java中,任何对象或基元类型都可以是数组。数组指标通过arrayName [index]访问,例如myArray[0] 。数组中的值是通过myArray [0] = value设置的,例如,如果myArray是String [] myArray[0] = "test"; 类型的数组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();
    }       
}