Home > Java > javaTutorial > How to Easily Convert Java Arrays to ArrayLists?

How to Easily Convert Java Arrays to ArrayLists?

Mary-Kate Olsen
Release: 2024-12-23 05:26:49
Original
526 people have browsed it

How to Easily Convert Java Arrays to ArrayLists?

Easily Convert Arrays to ArrayLists using Java

Storing data in arrays is common in Java, but sometimes you may need to work with collections like ArrayLists. Creating an ArrayList from an array is a straightforward process.

Converting an Array to ArrayList

Consider an Element[] array contains Element objects:

Element[] array = {new Element(1), new Element(2), new Element(3)};
Copy after login

To convert this array into an ArrayList, simply use the Arrays.asList() method:

ArrayList<Element> arrayList = new ArrayList<>(Arrays.asList(array));
Copy after login

Example Usage

Here's an example to illustrate the conversion:

// Create an Element array
Element[] array = {new Element(1), new Element(2), new Element(3)};

// Convert the array to ArrayList
ArrayList<Element> arrayList = new ArrayList<>(Arrays.asList(array));

// Iterate over the ArrayList
for (Element element : arrayList) {
    System.out.println(element);
}
Copy after login

The above is the detailed content of How to Easily Convert Java Arrays to ArrayLists?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template