Java Programming Tutorials

Java programming tutorials with many code examples!

Java add array to list


In Java there is a couple of ways to add an array of items to a collection. In the following examples we’ll cover a few of them.


When programming in Java, very often there’s a need to add some elements to a collection. It can be done in different ways as you can see in the following example:


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

public class CollectionsAddAll {

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

        // Too verbose:

        // Sometimes better:
        items.addAll(Arrays.asList("as", "an", "array"));

        // The best way: reuse!
        Collections.addAll(items, "reusing", "Collections", "library");

Many people don’t even know that there’s a method java.util.Collections.addAll(Collection, T… items) to add an array (so varargs too) of elements to a Collection. In most cases the method is better than Arrays.asList version.

Remember Item 47: Know and use the libraries from excellent “Effective Java, 2nd Edition” book! It will return many times! :-)

Was it helpful? Share!