How do I fill arrays in Java?

后端 未结 8 1668
旧巷少年郎
旧巷少年郎 2020-11-27 14:09

I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn\'t get anything he

相关标签:
8条回答
  • 2020-11-27 14:48
    int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    0 讨论(0)
  • 2020-11-27 14:49

    In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:

    int[] data = IntStream.generate(() -> value).limit(size).toArray();
    

    Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.

    Demo.

    0 讨论(0)
  • 2020-11-27 14:50

    You can also do it as part of the declaration:

    int[] a = new int[] {0, 0, 0, 0};
    
    0 讨论(0)
  • 2020-11-27 14:50
    Arrays.fill(arrayName,value);
    

    in java

    int arrnum[] ={5,6,9,2,10};
    for(int i=0;i<arrnum.length;i++){
      System.out.println(arrnum[i]+" ");
    }
    Arrays.fill(arrnum,0);
    for(int i=0;i<arrnum.length;i++){
      System.out.println(arrnum[i]+" ");
    }
    

    Output

    5 6 9 2 10
    0 0 0 0 0
    
    0 讨论(0)
  • 2020-11-27 14:51

    Check out the Arrays.fill methods.

    int[] array = new int[4];
    Arrays.fill(array, 0);
    
    0 讨论(0)
  • 2020-11-27 14:51

    An array can be initialized by using the new Object {} syntax.

    For example, an array of String can be declared by either:

    String[] s = new String[] {"One", "Two", "Three"};
    String[] s2 = {"One", "Two", "Three"};
    

    Primitives can also be similarly initialized either by:

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

    Or an array of some Object:

    Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
    

    All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.

    0 讨论(0)
提交回复
热议问题