David
0
Q:

java fill list

// -- Filling with fill() method example:
List<String> arrlist = new ArrayList<String>();  
//Add elements in the list  
arrlist.add("one");  
arrlist.add("two");  
arrlist.add("three");  
// contents of list: [AAA, BBB, CCC]

//Fill the list with 'four'  
Collections.fill(arrlist,"four");  
// contents of list: [four, four, four]

// -- Second example                
List<Integer> arrList = Arrays.asList(1,2,3,4);      
//Fill the list with 551  
Collections.fill(arrList,42);
// contents of list: [42, 42, 42]
1
// To fill with value
int array[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
Arrays.fill(array, 10);
// [10, 10, 10, 10, 10, 10, 10, 10, 10]

// Fill from index 1 to index 4. 
Arrays.fill(array, 1, 5, 10); ); 
// [2, 10, 10, 10, 10, 2, 2, 2, 2]

// For multidimensional arrays:
// Fill each row with 10. 
int [][]array2D = new int [3][4]; 
for (int[] row : array2D) 
  Arrays.fill(row, 10); 
// [[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]

// Fill each row with -1.
int[][][]array3D = new int[3][4][5]; 
for (int[][] row : array3D ) { 
  for (int[] rowColumn : row) { 
    Arrays.fill(rowColumn, -1); 
  } 
} 
1
//x is the list and value is what it is to be set to
for (int i = 0; i < x.length; i++) {
  x[i] = value;
}
1

New to Communities?

Join the community