Java Programming Tutorials

Java programming tutorials with many code examples!

Java add array to list

Problem:

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.

Solution:

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:

package com.farenda.java;

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:
        items.add("added");
        items.add("manually");
        System.out.println(items);

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

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

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! :-)

Share with the World!