remplir list Java rapidemnet

To fill a list in Java quickly, you can use the addAll method from the java.util.Collections class. This method allows you to add all elements from another collection to an existing list. Here's an example:

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class FillListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Create a separate collection with elements to add
        List<String> elementsToAdd = new ArrayList<>();
        elementsToAdd.add("Element 1");
        elementsToAdd.add("Element 2");
        elementsToAdd.add("Element 3");

        // Use the addAll method to fill the list quickly
        Collections.addAll(list, elementsToAdd.toArray(new String[0]));

        // Print the filled list
        System.out.println(list);
    }
}

In this example, we first create an empty ArrayList called list. Then, we create another ArrayList called elementsToAdd and add the elements that we want to fill the list with. Finally, we use the addAll method from the Collections class to add all elements from elementsToAdd to list. This allows us to quickly fill the list with the desired elements.

Note that we use the toArray method to convert the elementsToAdd list to an array, which is required by the addAll method. The new String[0] argument specifies that we want to create a new array of type String with a length of 0, and the toArray method will automatically resize the array as needed.

When you run this code, it will output:

[Element 1, Element 2, Element 3]

This demonstrates how you can quickly fill a list in Java using the addAll method.