首页 文章

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

提问于
浏览
1737

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

21 回答

  • 2313
    Type[] variableName = new Type[capacity];
    
    Type[] variableName = {comma-delimited values};
    
    
    
    Type variableName[] = new Type[capacity]; 
    
    Type variableName[] = {comma-delimited values};
    

    也是有效的,但我更喜欢类型之后的括号,因为更容易看到变量的类型实际上是一个数组 .

  • -6

    如果你想使用反射创建数组,那么你可以这样做:

    int size = 3;
     int[] intArray = (int[]) Array.newInstance(int.class, size );
    
  • 0

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

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

    要么

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

    此外,如果您想要更动态的东西,还有List接口 . 这不会表现得那么好,但更灵活:

    List<String> listOfString = new ArrayList<String>();
    
    listOfString.add("foo");
    listOfString.add("bar");
    
    String value = listOfString.get(0);
    assertEquals( value, "foo" );
    
  • 9

    为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]]
    
  • 8

    有两种类型的数组 .

    一维数组

    默认值的语法:

    int[] num = new int[5];
    

    或者(不太喜欢)

    int num[] = new int[5];
    

    给定值的语法(变量/字段初始化):

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

    或者(不太喜欢)

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

    注意:为了方便int [] num更可取,因为它清楚地告诉你这里是关于数组的 . 否则没什么区别 . 一点也不 .

    多维数组

    宣言

    int[][] num = new int[5][2];
    

    要么

    int num[][] = new int[5][2];
    

    要么

    int[] num[] = new int[5][2];
    

    初始化

    num[0][0]=1;
     num[0][1]=2;
     num[1][0]=1;
     num[1][1]=2;
     num[2][0]=1;
     num[2][1]=2;
     num[3][0]=1;
     num[3][1]=2;
     num[4][0]=1;
     num[4][1]=2;
    

    要么

    int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
    

    粗糙阵列(或非矩形阵列)

    int[][] num = new int[5][];
     num[0] = new int[1];
     num[1] = new int[5];
     num[2] = new int[2];
     num[3] = new int[3];
    

    所以我们在这里明确定义列 .
    Another Way:

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

    用于访问:

    for (int i=0; i<(num.length); i++ ) {
        for (int j=0;j<num[i].length;j++)
            System.out.println(num[i][j]);
    }
    

    或者:

    for (int[] a : num) {
      for (int i : a) {
        System.out.println(i);
      }
    }
    

    粗糙的数组是多维数组 .
    有关解释,请参阅the official java tutorials处的多维数组详细信息

  • 5

    我发现如果您理解每个部分会很有帮助:

    Type[] name = new Type[5];
    

    Type[] 是名为name的变量的类型("name"称为标识符) . 文字"Type"是基本类型,括号表示这是该基数的数组类型 . 数组类型依次是它们自己的类型,它允许您创建多维数组,如 Type[][] (Type []的数组类型) . 关键字 new 表示为新数组分配内存 . 括号之间的数字表示新数组的大小和分配的内存量 . 例如,如果Java知道基类型 Type 需要32个字节,并且您需要大小为5的数组,则需要在内部分配32 * 5 = 160个字节 .

    您还可以使用已存在的值创建数组,例如

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

    它不仅会创建空白空间,还会使用这些值填充它 . Java可以告诉基元是整数,并且它们中有5个,因此可以隐式确定数组的大小 .

  • 6

    数组是项目的顺序列表

    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 以使用 new Type(..) 初始化它们,类如 StringInteger 是特殊情况,将按以下方式处理

    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 维数组在空间方面是昂贵的 . 因为当你在所有维上创建一个 M 维数组 N 时,数组的总大小大于 N^M ,因为每个数组都有一个引用,而在M维上有一个(M-1)维数组参考文献 . 总大小如下

    Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
    //      ^                              ^ array reference
    //      ^ actual data
    
  • 117
    int[] SingleDimensionalArray = new int[2]
    
    int[][] MultiDimensionalArray = new int[3][4]
    
  • 23

    以下显示了数组的声明,但未初始化该数组:

    int[] myIntArray = new int[3];
    

    以下显示了数组的声明和初始化:

    int[] myIntArray = {1,2,3};
    

    现在,以下还显示了数组的声明和初始化:

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

    但是第三个显示了匿名数组对象创建的属性,它由引用变量“myIntArray”指向,所以如果我们只写“new int [] {1,2,3};”那么这就是如何创建匿名数组对象 .

    如果我们只写:

    int[] myIntArray;
    

    这不是数组的声明,但以下语句使上述声明完成:

    myIntArray=new int[3];
    
  • 1

    声明和初始化ArrayList的另一种方法:

    private List<String> list = new ArrayList<String>(){{
        add("e1");
        add("e2");
    }};
    
  • 238

    您也可以使用 java.util.Arrays 执行此操作:

    List<String> number = Arrays.asList("1", "2", "3");
    
    Out: ["1", "2", "3"]
    

    这个很漂亮 simple 直截了当 . 我没有在其他答案中看到它,所以我想我可以添加它 .

  • 23

    制作数组有两种主要方法:

    这个,对于一个空数组:

    int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
    

    而这一个,对于一个初始化的数组:

    int[] array = {1,2,3,4 ...};
    

    您还可以创建多维数组,如下所示:

    int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
    int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
    
  • 32

    以原始类型 int 为例 . 有几种方法可以声明和 int 数组:

    int[] i = new int[capacity];
    int[] i = new int[] {value1, value2, value3, etc};
    int[] i = {value1, value2, value3, etc};
    

    在所有这些中,您可以使用 int i[] 而不是 int[] i .

    使用反射,您可以使用 (Type[]) Array.newInstance(Type.class, capacity);

    请注意,在方法参数中, ... 表示 variable arguments . 基本上,任何数字参数很好 . 使用代码更容易解释:

    public static void varargs(int fixed1, String fixed2, int... varargs) {...}
    ...
    varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
    varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
    

    在方法内部, varargs 被视为普通 int[] . Type... 只能在方法参数中使用,因此 int... i = new int[] {} 将无法编译 .

    请注意,将 int[] 传递给方法(或任何其他 Type[] )时,您无法使用第三种方式 . 在 int[] i = *{a, b, c, d, etc}* 语句中,编译器假定 {...} 表示 int[] . 但那是因为你要声明一个变量 . 将数组传递给方法时,声明必须是 new Type[capacity]new Type[] {...} .

    多维数组

    多维数组很难处理 . 本质上,2D数组是一个数组数组 . int[][] 表示 int[] 的数组 . 关键是如果 int[][] 被声明为 int[x][y] ,则最大索引为 i[x-1][y-1] . 基本上,矩形 int[3][5] 是:

    [0, 0] [1, 0] [2, 0]
    [0, 1] [1, 1] [2, 1]
    [0, 2] [1, 2] [2, 2]
    [0, 3] [1, 3] [2, 3]
    [0, 4] [1, 4] [2, 4]
    
  • 26

    您可以使用数组声明或数组文字(但只有在声明并立即影响变量时,才能使用数组文字重新分配数组) .

    对于原始类型:

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

    对于类,例如 String ,它是相同的:

    String[] myStringArray = new String[3];
    String[] myStringArray = {"a","b","c"};
    String[] myStringArray = new String[]{"a","b","c"};
    

    当您首先声明数组然后初始化它时,第三种初始化方法很有用 . 演员是必要的 .

    String[] myStringArray;
    myStringArray = new String[]{"a","b","c"};
    
  • 13

    或者,

    // Either method works
    String arrayName[] = new String[10];
    String[] arrayName = new String[10];
    

    这声明了一个名为 arrayName 且大小为10的数组(你要使用的元素为0到9) .

  • 7

    声明一个对象引用数组:

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

    要创建类对象的数组,可以使用 java.util.ArrayList . 定义一个数组:

    public ArrayList<ClassName> arrayName;
    arrayName = new ArrayList<ClassName>();
    

    为数组赋值:

    arrayName.add(new ClassName(class parameters go here);
    

    从数组中读取:

    ClassName variableName = arrayName.get(index);
    

    注意:

    variableName 是对数组的引用,意味着操纵 variableName 将操纵 arrayName

    for循环:

    //repeats for every value in the array
    for (ClassName variableName : arrayName){
    }
    //Note that using this for loop prevents you from editing arrayName
    

    for循环,允许您编辑 arrayName (常规for循环):

    for (int i = 0; i < arrayName.size(); i++){
        //manipulate array here
    }
    
  • 5

    在Java 9中

    使用不同的IntStream.iterateIntStream.takeWhile方法:

    int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();
    
    Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
    
    int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();
    
    Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    在Java 10中

    使用Local Variable Type Inference

    var letters = new String[]{"A", "B", "C"};
    
  • 26

    您可以通过多种方式在Java中声明数组:

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

    您可以在Sun tutorial站点和JavaDoc中找到更多信息 .

  • 1

    在Java 8中,您可以像这样使用 .

    String[] strs = IntStream.range(0, 15)  // 15 is the size
        .mapToObj(i -> Integer.toString(i))
        .toArray(String[]::new);
    

相关问题