如何在Java中声明和初始化数组?


当前回答

声明和初始化数组非常容易。例如,您希望在数组中保存5个整数元素,即1、2、3、4和5。您可以通过以下方式进行操作:

a)

int[] a = new int[5];

or

b)

int[] a = {1, 2, 3, 4, 5};

因此基本模式用于初始化,方法a)的声明是:

datatype[] arrayname = new datatype[requiredarraysize];

数据类型应为小写。

因此,基本模式用于初始化,方法a的声明是:

如果是字符串数组:

String[] a = {"as", "asd", "ssd"};

如果是字符数组:

char[] a = {'a', 's', 'w'};

对于浮点双精度,数组的格式将与整数相同。

例如:

double[] a = {1.2, 1.3, 12.3};

但是当您通过“方法a”声明和初始化数组时,您必须手动或通过循环或其他方式输入值。

但是,当您通过“方法b”执行此操作时,您不必手动输入值。

其他回答

这里有很多答案。我添加了一些创建数组的技巧(从考试的角度来看,知道这一点很好)

声明和定义数组intintArray[]=新int[3];这将创建一个长度为3的数组。由于它持有一个基元类型int,所有值默认设置为0。例如intArray[2];//将返回0在变量名称前使用方括号[]int[]intArray=新int[3];intArray[0]=1;//数组内容现在为{1,0,0}初始化并向阵列提供数据int[]intArray=新int[]{1,2,3};这一次,无需在方框括号中提及尺寸。甚至一个简单的变体是:int[]intArray={1,2,3,4};长度为0的数组int[]intArray=新int[0];int length=intArray.length;//将返回长度0类似于多维数组int intArray[][]=新int[2][3];//这将创建一个长度为2的数组//每个元素包含另一个长度为3的数组。// { {0,0,0},{0,0,0} }int lenght1=intArray.length;//将返回2int length2=intArray[0].length;//将返回3

在变量之前使用方括号:

    int[][] intArray = new int[2][3];

如果你在最后放一个盒子支架,那是绝对好的:

    int[] intArray [] = new int[2][4];
    int[] intArray[][] = new int[2][3][4]

一些示例

    int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
    int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
    int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
    // All the 3 arrays assignments are valid
    // Array looks like {{1,2,3},{4,5,6}}

每个内部元素的大小不一定相同。

    int [][] intArray = new int[2][];
    intArray[0] = {1,2,3};
    intArray[1] = {4,5};
    //array looks like {{1,2,3},{4,5}}

    int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.

如果使用上述语法,则必须确保向前方向必须在方括号中指定值。否则它将无法编译。一些示例:

    int [][][] intArray = new int[1][][];
    int [][][] intArray = new int[1][2][];
    int [][][] intArray = new int[1][2][3];

另一个重要特征是协变

    Number[] numArray = {1,2,3,4};   // java.lang.Number
    numArray[0] = new Float(1.5f);   // java.lang.Float
    numArray[1] = new Integer(1);    // java.lang.Integer
   // You can store a subclass object in an array that is declared
   // to be of the type of its superclass.
   // Here 'Number' is the superclass for both Float and Integer.

   Number num[] = new Float[5]; // This is also valid

重要信息:对于引用的类型,数组中存储的默认值为空。

声明对象引用数组:

class Animal {}

class Horse extends Animal {
    public static void main(String[] args) {

        /*
         * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
         */
        Animal[] a1 = new Animal[10];
        a1[0] = new Animal();
        a1[1] = new Horse();

        /*
         * Array of Animal can hold Animal and Horse and all subtype of Horse
         */
        Animal[] a2 = new Horse[10];
        a2[0] = new Animal();
        a2[1] = new Horse();

        /*
         * Array of Horse can hold only Horse and its subtype (if any) and not
           allowed supertype of Horse nor other subtype of Animal.
         */
        Horse[] h1 = new Horse[10];
        h1[0] = new Animal(); // Not allowed
        h1[1] = new Horse();

        /*
         * This can not be declared.
         */
        Horse[] h2 = new Animal[10]; // Not allowed
    }
}

公告

一维阵列

int[] nums1; // best practice
int []nums2;
int nums3[];

多维数组

int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];

声明和初始化

一维阵列

使用默认值

int[] nums = new int[3]; // [0, 0, 0]

Object[] objects = new Object[3]; // [null, null, null]

带数组文字

int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};

Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};

带有循环

int[] nums = new int[3];
for (int i = 0; i < nums.length; i++) {
    nums[i] = i; // can contain any YOUR filling strategy
}

Object[] objects = new Object[3];
for (int i = 0; i < objects.length; i++) {
    objects[i] = new Object(); // can contain any YOUR filling strategy
}

带循环for和Random

int[] nums = new int[10];
Random random = new Random();
for (int i = 0; i < nums.length; i++) {
    nums[i] = random.nextInt(10); // random int from 0 to 9
}

使用流(从Java 8开始)

int[] nums1 = IntStream.range(0, 3)
                       .toArray(); // [0, 1, 2]
int[] nums2 = IntStream.rangeClosed(0, 3)
                       .toArray(); // [0, 1, 2, 3]
int[] nums3 = IntStream.of(10, 11, 12, 13)
                       .toArray(); // [10, 11, 12, 13]
int[] nums4 = IntStream.of(12, 11, 13, 10)
                       .sorted()
                       .toArray(); // [10, 11, 12, 13]
int[] nums5 = IntStream.iterate(0, x -> x <= 3, x -> x + 1)
                       .toArray(); // [0, 1, 2, 3]
int[] nums6 = IntStream.iterate(0, x -> x + 1)
                       .takeWhile(x -> x < 3)
                       .toArray(); // [0, 1, 2]

int size = 3;
Object[] objects1 = IntStream.range(0, size)
        .mapToObj(i -> new Object()) // can contain any YOUR filling strategy
        .toArray(Object[]::new);

Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy
        .limit(size)
        .toArray(Object[]::new);

使用Random和Stream(从Java 8开始)

int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();

多维数组

使用默认值

int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]

带数组文字

int[][] nums1 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
int[][] nums2 = new int[][]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

Object[][] objects1 = {
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};

带有循环

int[][] nums = new int[3][3];
for (int i = 0; i < nums.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        nums[i][j] = i + j; // can contain any YOUR filling strategy
    }
}

Object[][] objects = new Object[3][3];
for (int i = 0; i < objects.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        objects[i][j] = new Object(); // can contain any YOUR filling strategy
    }
}

使用局部变量类型推断,您只需指定一次类型:

var values = new int[] { 1, 2, 3 };

Or

int[] values = { 1, 2, 3 }

有多种方法可以在Java中声明数组:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};

您可以在Sun教程网站和JavaDoc中找到更多信息。