StackTips

Converting Array to List in java

nilan avtar

Written by

Nilanchala,  2 min read,  2.55K views, updated on Sept. 17, 2023

Array class has a asList() method that helps to convert array to List. This method copies an array into List. When we use asList() method, the array and list both shares the same heap space. When update is made to the list, it reflects the changes to array and vice-versa.

import java.util.Arrays;
import java.util.List;

public class ArrayToList {

	public static void main(String[] args) {
		String[] names = { "Neel", "Clay", "Adams", "Joseph", "Jack" };

		// Converting Array to List 
		List aList = Arrays.asList(names);

		System.out.println("Size of list=" + aList.size());
		System.out.println("aList Values=" + aList);

		//changing the aList values
		aList.set(2, "Dinesh");

		// printing aList values
		for (String name : names) {
			System.out.println(name);
		}
	}
}

If you look at the output below you will notice that, after changing the values in list, the changes reflected in the array.

Output

Converting Array to List in java

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
nilan avtar

Nilanchala

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!