How to create an array in java so that it is immediately filled? Without for .

Is it possible to do so?

    2 answers 2

    When creating an instance of an array, you can give it values ​​in braces, separated by commas

     Object[] objArray = new Object[]{new Object(), new Object(), new Object()}; //или Object[] objArray = {new Object(), new Object(), new Object()}; String[] stringArray = new String[]{"1","2","3"}; //или String[] stringArray = {"1","2","3"}; int[] intArray = new int[]{1,2,3}; //или int[] intArray = {1,2,3}; 

    To fill an array with initial identical data, you can use Arrays.fill() like this :

     int [] myarray = new int[num_elts]; Arrays.fill(myarray, 42); 

    or so:

     Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]); //[42, 42, 42] 

    but this method also uses a loop.

    • I know that. Is it possible for everyone to have the same? Suppose I want to create an array of boolean all of true - DumbHacker
    • @ BluntHacker, updated the answer - YuriySPb
    • @zRrr, added this in response) - YuriySPb
    • Is it possible to use Arryas to fill in an empty array of different values? To not the same - BluntHacker
    • one
      @ BluntHacker, here only if manually, as written at the beginning of the answer. Or do you somehow imagine this for yourself? How can you even more simplify the simple enumeration of values ​​for the cells of an array? - Yuriy SPb
     Arrays.fill(array, -1); 

    P. C. Found in Google in 17 seconds as requested by java init array with one value