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 TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API