How to Fill Or Replace Elements of a List in Java


This example will explain the method to replace all of the elements of the specified list with the same value.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class FillListExample {
 
    public static void main(String a[]){
         
        List list = new ArrayList();
        list.add("1");
        list.add("2");
        list.add("3");
        System.out.println("Original List: " + list);
        // fill elements
        Collections.fill(list, "java");
        System.out.println("After fill: " + list);
    }
}

Output:

Original List: [1, 2, 3]
After fill: [java, java, java]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments