How to create an array in java so that it is immediately filled? Without for .
Is it possible to do so?
How to create an array in java so that it is immediately filled? Without for .
Is it possible to do so?
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.
Arrays.fill(array, -1); P. C. Found in Google in 17 seconds as requested by java init array with one value
Source: https://ru.stackoverflow.com/questions/535825/
All Articles