Java arraylist copy all

Class ArrayList

Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(. ));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

Содержание
  1. Copy Elements of One ArrayList to Another ArrayList in Java
  2. Copy elements from one ArrayList to another ArrayList
  3. Top Related Articles:
  4. About the Author
  5. Comments
  6. Copy ArrayList in Java
  7. Copy ArrayList to Another by Passing It to Another ArrayList’s Constructor
  8. Copy ArrayList to Another Using the addAll() Fuction
  9. Copy ArrayList Using Java 8 Stream
  10. Copy ArrayList to Another Using the clone() Method
  11. Related Article — Java ArrayList
  12. Java ArrayList copy elements example
  13. How to copy ArrayList elements to another ArrayList in Java?
  14. 1) Copy ArrayList using the copy method of Collections class
  15. 2) Copy ArrayList using the addAll method
Читайте также:  Class to java conversion

Copy Elements of One ArrayList to Another ArrayList in Java

In this tutorial, we will write a java program to copy elements of one ArrayList to another ArrayList in Java. We will be using addAll() method of ArrayList class to do that.

public boolean addAll(Collection c)

When we call this method like this:

It appends all the elements of oldList to the newList . It throws NullPointerException , if oldList is null.
Note: This method doesn’t clone the ArrayList, instead it appends the elements of one ArrayList to another ArrayList.

Copy elements from one ArrayList to another ArrayList

In the following example, we have an ArrayList al that contains three elements. We have another List list that contains some elements, we are copying the elements of list to the al . This is done using addAll() method, which copies the elements of one List to another another list. This operation doesn’t remove the existing elements of the list, in which the elements are copied.

import java.util.ArrayList; import java.util.List; public class ListToArrayListExample < public static void main(String a[])< ArrayListal = new ArrayList(); //Adding elements to the ArrayList al.add("Text 1"); al.add("Text 2"); al.add("Text 3"); System.out.println("ArrayList Elements are: "+al); //Adding elements to a List List list = new ArrayList(); list.add("Text 4"); list.add("Text 5"); list.add("Text 6"); //Adding all elements of list to ArrayList using addAll al.addAll(list); System.out.println("Updated ArrayList Elements: "+al); > >
ArrayList Elements are: [Text 1, Text 2, Text 3] Updated ArrayList Elements: [Text 1, Text 2, Text 3, Text 4, Text 5, Text 6]

Recommended Articles:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

@ Himanshu, ArrayList never be a null, instead it is an empty when u create. if you want more clarity, execute the below code. List list = new ArrayList();
List newList = new ArrayList();
list.addAll(newList);
System.out.println(list); // this works fine and creates a list with empty List list = null;
List newList = null;
list.addAll(newList);
System.out.println(list); // this will give you NPE. since List is not initiated with any of its implemented class

Источник

Copy ArrayList in Java

Copy ArrayList in Java

  1. Copy ArrayList to Another by Passing It to Another ArrayList’s Constructor
  2. Copy ArrayList to Another Using the addAll() Fuction
  3. Copy ArrayList Using Java 8 Stream
  4. Copy ArrayList to Another Using the clone() Method
Читайте также:  Тег IMG

After we have introduced how to copy array in Java in another article, we will introduce four methods to copy an ArrayList to another ArrayList in Java in this article. We will use the same elements in every example to copy an ArrayList using different methods.

Copy ArrayList to Another by Passing It to Another ArrayList’s Constructor

An ArrayList in Java can have three types of constructor. We can create an ArrayList object with an empty constructor, with initial size, or a collection in which the ArrayList is created using the collection’s elements.

We will use the third type of constructor; we first create an ArrayList names1 with an empty constructor and then add some random names. We create a new ArrayList names2 to copy the elements of names1 to it and pass names1 to the constructor new ArrayList<>(names1) .

At last, we print the whole names2 ArrayList using forEach that prints each element.

import java.util.ArrayList;  public class CopyArrayList   public static void main(String[] args)   ArrayListString> names1 = new ArrayList<>();  names1.add("Alan");  names1.add("Alex");  names1.add("Bob");  names1.add("Bryan");  names1.add("Cathy");  names1.add("Drake");   ArrayListString> names2 = new ArrayList<>(names1);   names2.forEach(System.out::println);   > > 
Alan Alex Bob Bryan Cathy Drake 

Copy ArrayList to Another Using the addAll() Fuction

ArrayList comes with a function addAll() that takes a Collection as an argument and adds or appends the given collection’s elements at the end of the ArrayList if there are existing elements. ArrayList implements Collection , which allows us to use the ArrayList names1 as an argument of the addAll() method.

names1 contains a few elements that should be copied to the newly created empty Arraylist names2 . And it is done by names2.addAll(names1) . The output shows the copied elements of names2 .

import java.util.ArrayList;  public class CopyArrayList   public static void main(String[] args)   ArrayListString> names1 = new ArrayList<>();  names1.add("Alan");  names1.add("Alex");  names1.add("Bob");  names1.add("Bryan");  names1.add("Cathy");  names1.add("Drake");   ArrayListString> names2 = new ArrayList<>();  names2.addAll(names1);   names2.forEach(System.out::println);   > > 
Alan Alex Bob Bryan Cathy Drake 

Copy ArrayList Using Java 8 Stream

In this example, we use the new Stream API introduced in Java 8. We create an ArrayList with elements, then call the stream() method with names1 to use the stream methods like the collect() method that collects the stream and folds it into a list using Collectors.toList() .

This stream returns a List, which needs to be cast to an ArrayList.

import java.util.ArrayList; import java.util.stream.Collectors;  public class CopyArrayList   public static void main(String[] args)   ArrayListString> names1 = new ArrayList<>();  names1.add("Alan");  names1.add("Alex");  names1.add("Bob");  names1.add("Bryan");  names1.add("Cathy");  names1.add("Drake");   ArrayListString> names2 = (ArrayListString>) names1.stream().collect(Collectors.toList());   names2.forEach(System.out::println);   > > 
Alan Alex Bob Bryan Cathy Drake 

Copy ArrayList to Another Using the clone() Method

The last method is the clone() method that is a native ArrayList method. It copies the elements and returns a new List, similar to the previous solution. We create an ArrayList with elements and call the clone() method. At last, we cast the returned results to ArrayList to get our desired result.

import java.util.ArrayList;  public class CopyArrayList   public static void main(String[] args)   ArrayListString> names1 = new ArrayList<>();  names1.add("Alan");  names1.add("Alex");  names1.add("Bob");  names1.add("Bryan");  names1.add("Cathy");  names1.add("Drake");   ArrayListString> names2 = (ArrayListString>) names1.clone();   names2.forEach(System.out::println);   > > 
Alan Alex Bob Bryan Cathy Drake 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java ArrayList

Copyright © 2023. All right reserved

Источник

Java ArrayList copy elements example

Java ArrayList copy elements example shows how to copy ArrayList elements to another ArrayList. The example also shows how to copy all elements of ArrayList to another ArrayList using various approaches.

How to copy ArrayList elements to another ArrayList in Java?

There are several ways to copy ArrayList elements to another ArrayList as given below.

1) Copy ArrayList using the copy method of Collections class

You can copy elements of one ArrayList to another using copy method of the Collections class.

This method copies all elements from the source list to the destination list. Index of the destination list elements will be the same after the copy operation.

As you can see from the output, elements of the aListWeekend are copied to the aListDays at the identical index such that the first element of the source list becomes the first element of destination list and so on.

Note 1: If the destination list is larger than the source list, all remaining elements of the destination list will be kept as is. i.e. if the source list contains 2 elements and destination contains 5, after the copy, the destination list will still retain its last 3 elements. Consider below given example.

As you can see from the output, “Four” is copied at first index in the destination list but it still retained “Two” and “Three” elements.

Note 2: If the destination list is not large enough to contain all the elements of the source list, copy method throws IndexOutOfBoundException. Consider below given example.

2) Copy ArrayList using the addAll method

You can use the addAll method to copy elements of ArrayList to another ArrayList.

The addAll method appends all elements of the specified collection to the end of the ArrayList.

Источник

Оцените статью