How to Initialize a List in Java
Table of Contents
Lists are really useful in Java because they allow you to store a collection of items in a single variable.
When you're working with Java, it is very likely that eventually you'll need to create one yourself.
In this post, we'll learn how to initialize a list in Java.
How to initialize a list from an array in Java
The easiest way to initialize a list in Java is to initialize one using an existing array.
Let's define an array of strings:
JAVAString[] names = {"John", "Mary", "Peter"};
Now, we can initialize a list from this array using the Arrays.asList()
method.
This method takes an array as an argument and returns a list containing the same elements as the array:
JAVAString[] names = {"John", "Mary", "Peter"};
List<String> namesList = Arrays.asList(names);
How to initialize a list from individual elements in Java
Another way to initialize a list in Java is to initialize it from individual elements.
This means, you don't need to create an array first, you can just pass the elements directly to the Arrays.asList()
method.
Let's see how this works:
JAVAList<String> namesList = Arrays.asList("John", "Mary", "Peter");
This is useful when you don't have an array of elements, but you want to initialize a list from individual elements.
How to initialize a list and then add elements to it in Java
Another way to create a list in Java is to initialize an empty list and then add elements to it using the add()
method.
Let's see how this works:
JAVAList<String> namesList = new ArrayList<>();
namesList.add("John");
namesList.add("Mary");
namesList.add("Peter");
Finally, another way to do it is by initializing it in the constructor using double-brace initialization:
JAVAList<String> namesList = new ArrayList<String>() {{
add("John");
add("Mary");
add("Peter");
}};
For the most part, unless you need to use double-brace initialization, you should instead separately initialize the list and then add elements to it because it is more clear and readable.
Conclusion
In this post, we learned how to initialize a list in Java.
Your options include initializing a list from an array, initializing a list from individual elements, and initializing a list and then adding elements to it.
Thanks for reading and happy coding!
- Getting Started with Solid
- Getting Started with Express
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js