Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65

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:

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:

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

Share with the World!