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

How to Easily Convert Java Arrays to ArrayLists?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 05:26:49571browse

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)};

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

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

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);
}

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!

Statement:
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