Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java List copy

farenda 2015-07-15 0

Problem:

There is a number of ways do to Java List copy. Which one is best? Which one apply to your situation at hand? In this post you will find this out!

Solution:

The following Java program demonstrates how to do Java List copy using copy constructor and Collections.copy(List dest, List src) method:

package com.farenda.java;

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

import static java.util.Arrays.asList;

public class CollectionsCopy {

    public static void main(String[] args) {
        usingCopyConstructor();

        copySourceToSmallerDest();

        copySameSizeLists();

        copySourceToBiggerDest();

        copyToUnmodifiableDest();
    }

    private static void usingCopyConstructor() {
        List<Integer> source = asList(1, 2, 3);
        List<Integer> dest = new ArrayList<>(source);
        System.out.printf("%nCopy %s to %s using copy constructor.%n",
                          source, dest);
    }

    private static void copySourceToSmallerDest() {
        List<Integer> source = asList(1, 2, 3);
        // The same for: new ArrayList<>(source.size());
        List<Integer> dest = asList(4, 5);

        System.out.printf("%nCopy %s to (smaller) %s%n", source, dest);
        try {
            Collections.copy(dest, source);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
    }

    private static void copySameSizeLists() {
        List<Integer> source = asList(1, 2);
        List<Integer> dest = asList(3, 4);

        System.out.printf("%nCopy %s to (same size) %s%n", source, dest);
        Collections.copy(dest, source);
        System.out.println("source: " + source);
        System.out.println("destination: " + dest);
    }

    private static void copySourceToBiggerDest() {
        List<Integer> source = asList(1, 2);
        List<Integer> dest = asList(3, 4, 5);

        System.out.printf("%nCopy %s to (bigger) %s%n", source, dest);
        Collections.copy(dest, source);
        System.out.println("source: " + source);
        System.out.println("destination: " + dest);
    }

    private static void copyToUnmodifiableDest() {
        List<Integer> source = asList(1, 2);
        List<Integer> dest = Collections.unmodifiableList(asList(4, 5));

        System.out.printf("%nCopy %s to (unmodifiable) %s%n", source, dest);
        try {
            Collections.copy(dest, source);
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        }
    }
}

As you can see the easiest way of copying Lists is to use copy constructor that’s available in List implementations – here it’s ArrayList. It copies references to all elements (so it is a shallow copy) from source list into the new list.

Sometimes you may want to update an existing List with a new data. In such case Collections.copy(List dest, List src) performs really well. The method sets elements on the same positions in dest List and doesn’t re-size target list when needed. So, remember that dest List have to be of at least size of source List and allow for modifications. These corner cases are illustrated in the 4 copy… methods in the example above.

Running the above Java code gives the following result:

Copy [1, 2, 3] to [1, 2, 3] using copy constructor.

Copy [1, 2, 3] to (smaller) [4, 5]
java.lang.IndexOutOfBoundsException: Source does not fit in dest
        at java.util.Collections.copy(Collections.java:556)
        at com.farenda.java.CollectionsCopy.copySourceToSmallerDest(CollectionsCopy.java:36)
        at com.farenda.java.CollectionsCopy.main(CollectionsCopy.java:14)

Copy [1, 2] to (same size) [3, 4]
source: [1, 2]
destination: [1, 2]

Copy [1, 2] to (bigger) [3, 4, 5]
source: [1, 2]
destination: [1, 2, 5]

Copy [1, 2] to (unmodifiable) [4, 5]
java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableList.set(Collections.java:1311)
        at java.util.Collections.copy(Collections.java:561)
        at com.farenda.java.CollectionsCopy.copyToUnmodifiableDest(CollectionsCopy.java:68)
        at com.farenda.java.CollectionsCopy.main(CollectionsCopy.java:20)

If you know a good use case for Collections.copy(List dest, List src) then let me know. Thanks! :-)

Share with the World!
Categories Java Tags java-collections
Previous: Kill tasks to increase productivity
Next: Java contains any

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored