Java Filling List elements with fill()

Java Filling List elements with fill()

With the Collections fill() static method (Collections methods are known as algorithms), a data structure can be filled up (or replaced) with one element. After this method call, the data structure will have the same element.

Following is the method signature

  • static void fill(List list1, Object obj1): Replaces all the elements of list1 with obj1. Earlier elements are lost. This method is used to fill all the elements with the same values.

Following program uses the above method.

Java Filling List elements with fill()
Output screenshot of Java Filling List elements with fill()

ArrayList myList = new ArrayList();
myList.add(50);

An ArrayList object myList is created and added four integer elements with add() method inherited from List interface.

Collections.fill(myList, 0);

All the four elements are replaced with 0 value.

ArrayList namesList = new ArrayList();
namesList.add(“hello”);

Another ArrayList object namesList is created and added with three string elements.

Collections.fill(namesList, null);

All the three string elements are replaced with null values using fill() method. This method is very useful to fill all the elements with the same value (or one value only).

Leave a Reply

Your email address will not be published. Required fields are marked *