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 Svelte
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript