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


当前回答

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

声明和定义数组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

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

其他回答

用于使用0以外的默认值进行初始化:

var arr = new int[1000];
Arrays.fill(arr, 1);

声明对象引用数组:

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
    }
}

声明和初始化数组非常容易。例如,您希望在数组中保存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”执行此操作时,您不必手动输入值。

为Java 8和更高版本声明和初始化。创建一个简单的整数数组:

int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

为[-50,50]之间的整数和双[0,1E17]创建随机数组:

int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();

两个序列的功率:

double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]

对于String[],必须指定构造函数:

String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));

多维数组:

String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
    .toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]

数组是项目的顺序列表

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

如果它是一个物体,那么它就是同一个概念

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

对于对象,您需要将其赋值为null,以使用新的Type(..)初始化它们,像String和Integer这样的类是特殊情况,将按如下方式处理

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

通常,您可以创建M维数组

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

值得注意的是,从空间角度来看,创建M维阵列是昂贵的。因为当您在所有维度上创建一个N的M维数组时,数组的总大小大于N^M,因为每个数组都有一个引用,并且在M维有一个(M-1)维引用数组。总尺寸如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data