Java как скопировать arraylist

ArrayList clone() method in Java

In this tutorial, we will see examples of ArrayList clone() method. This method creates a shallow copy of an ArrayList.

Creates a shallow copy of oldList and assign it to newList .

Example 1: Creating a copy of an ArrayList using clone()

In this example, we have an ArrayList of String type and we are cloning it to another ArrayList using clone() method. The interesting point to note here is that when we added and removed few elements from original ArrayList al after the clone() method, the another ArrayList al2 didn’t get affected. It shows that clone() method just returns a shallow copy of ArrayList.

import java.util.ArrayList; public class Details < public static void main(String a[])< ArrayListal = new ArrayList(); //Adding elements to the ArrayList al.add("Apple"); al.add("Orange"); al.add("Mango"); al.add("Grapes"); System.out.println("ArrayList: "+al); ArrayList al2 = (ArrayList)al.clone(); System.out.println("Shallow copy of ArrayList: "+ al2); //add and remove from original ArrayList al.add("Fig"); al.remove("Orange"); //print both ArrayLists after add & remove System.out.println("Original ArrayList:"+al); System.out.println("Cloned ArrayList:"+al2); > >
ArrayList: [Apple, Orange, Mango, Grapes] Shallow copy of ArrayList: [Apple, Orange, Mango, Grapes] Original ArrayList:[Apple, Mango, Grapes, Fig] Cloned ArrayList:[Apple, Orange, Mango, Grapes]

Example 2: Clone Integer ArrayList

In the following example, we are creating a shallow copy of an Integer ArrayList using clone() method. This example is similar to the first example, except that here list contains integers.

import java.util.ArrayList; public class JavaExample < public static void main(String args[]) < // Creating an ArrayList ArrayListnumbers = new ArrayList(); // Adding elements to the arraylist numbers.add(3); numbers.add(7); numbers.add(5); numbers.add(11); numbers.add(9); // print first ArrayList System.out.println("Original ArrayList: "+ numbers); // Creating another ArrayList // Copying the array list "numbers" to this list ArrayList copyList = (ArrayList)numbers.clone(); // Displaying the other linked list System.out.println("Second ArrayList: "+ copyList); > >
Original ArrayList: [3, 7, 5, 11, 9] Second ArrayList: [3, 7, 5, 11, 9]

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

Hello sir…The clone program doesn’t compile at all…
when complied..It says..
“Note: Java uses unchecked or unsafe operation ”
” Note: recompile with -Xlint: unchecked for details ” What could be the meaning of this ..How can I rectify it.

Читайте также:  Php равны ли массивы

Источник

Клонировать список в Java

В этом посте мы обсудим, как клонировать список в Java. Нам нужно построить список, содержащий указанные элементы списка в том же порядке, что и исходный список.

Предположим, что в списке нет изменяемых объектов, т. е. код может выполнять мелкая копия.

1. Использование конструктора копирования

Мы можем использовать конструктор копирования для клонирования списка, который представляет собой специальный конструктор для создания нового объекта как копии существующего объекта.

2. Использование addAll(Collection c) метод

List интерфейс имеет addAll() метод, который добавляет все элементы указанной коллекции в конец списка. Мы можем использовать то же самое для копирования элементов из исходного списка в пустой список.

3. Использование Java 8

Мы также можем использовать потоки в Java 8 и выше для клонирования списка, как показано ниже:

4. Использование Object.clone() метод

Java Object класс обеспечивает clone() метод, который можно переопределить, реализуя Cloneable интерфейс. Идея состоит в том, чтобы пройтись по списку, клонировать каждый элемент и добавить его в клонированный список. Мы также можем использовать Java 8 Stream, чтобы сделать то же самое.

5. Использование Apache Commons Lang

Несколько сторонних библиотек предоставляют удобные классы для Сериализация и десериализация объектов. Один из таких классов SerializationUtils предоставленный Apache Commons Lang, который serialize() а также deserialize() методы сериализации/десериализации объекта. Сериализованный объект не содержит ссылки на исходный объект при десериализации.

SerializationUtils также обеспечивает clone() метод, который показан ниже:

Источник

Copy a List to Another List in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Читайте также:  Java bytes int double

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Источник

Как скопировать arraylist java

Чтобы скопировать ArrayList , можно использовать метод clone() , который создаст копию списка. Также можно создать новый объект ArrayList и использовать метод addAll() для добавления всех элементов из исходного списка в новый список.

ArrayListString> originalList = new ArrayList<>(); // добавляем элементы в оригинальный список originalList.add("один"); originalList.add("два"); originalList.add("три"); // создаем новый список и добавляем все элементы из оригинального списка ArrayListString> copiedList = new ArrayList<>(); copiedList.addAll(originalList); // проверяем, что списки одинаковые System.out.println(originalList.equals(copiedList)); // => true 

Также можно использовать конструктор ArrayList(Collection c) , который создает новый список на основе коллекции. Например:

ArrayListString> originalList = new ArrayList<>(); // добавляем элементы в оригинальный список originalList.add("один"); originalList.add("два"); originalList.add("три"); // создаем новый список на основе оригинального ArrayListString> copiedList = new ArrayList<>(originalList); // проверяем, что списки одинаковые System.out.println(originalList.equals(copiedList)); // => true 

Источник

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

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

Источник

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