Sunday, April 14, 2024
HomeSoftware EngineeringThe right way to create ArrayList from Array in Java

The right way to create ArrayList from Array in Java


The issue

If in case you have a conventional array, that appears one thing like the next:

A[] array = {new A(1), new A(2), new A(3)};

And also you want to convert this to an ArrayList:

ArrayList<Ingredient> arraylist = ???;

..then you are able to do the next!

The answer

The method

new ArrayList<>(Arrays.asList(array));

The right way to use it

After all you might at all times simplify this one additional immediately as:

Record<ClassName> record = Arrays.asList(array)

The right way to previous Java

In case you are caught within the previous world of Java, you possibly can fall again to:

Record<ClassName> record  = new ArrayList<ClassName>(Arrays.asList(array));
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments