How To Declare And Initialize A List With Values In Java (ArrayList ...
Maybe your like
Javarevisited
Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions
Topics and Categories
- core java
- spring
- hibernate
- collections
- multithreading
- design patterns
- interview questions
- coding
- data structure
- OOP
- java 8
- books
- About Me
- Java Certifications
- JDBC
- jsp-servlet
- JSON
- SQL
- Linux
- Courses
- online resources
- jvm-internals
- REST
- Eclipse
- jQuery
- Java IO
- Java XML
Monday, June 30, 2025
How to declare and initialize a List with values in Java (ArrayList/LinkedList) - Arrays.asList() Example Hello guys, today, I am going to share with you a useful tip to initialize a List like ArrayList or LinkedList with values, which will help you a lot while writing unit tests and prototypes. Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs like the collection literals of Scala, but there is a trick which you can use to declare and initialize a List at the same time. This trick is also known as initializing a List with values. I have used this trick a lot while declaring list for unit testing and writing demo programs to understand an API etc and today I'll you'll also learn that. If you have been using Java programming language for quite some time then you must be familiar with the syntax of an array in Java and how to initialize an array in the same line while declaring it as shown below: String[] oldValues = new String[] {"list" , "set" , "map"} or even shorter : String[] values = {"abc","bcd", "def"}; Similarly, we can also create a List and initialize it at the same line, popularly known as initializing List in one line example. Arrays.asList() is used for that purpose which returns a fixed size List backed by Array, but there are some problems with that as you cannot add or remove elements on that list. By the way, don’t get confused between Immutable or read-only List which doesn’t allow any modification operation including set(index) which is permitted in fixed-length List. You can further see a good Java course like The Complete Java Masterclass to learn more about the Immutable list in Java.Java program to Create and initialize List in one line
Now that we know how to create and initialize the list at the same line, let's see an example of how to use this trick in a Java program. Here is a Java program that creates and initializes List in one line using Array. The Arrays.asList() method is used to initialize List in one line and it takes an Array which you can create at the time of calling this method itself. It also uses Generics to provide type-safety and this example can be written using Generics as well. But the drawback is that it returns a fixed size ArrayList which means you cannot add and remove elements if you want. You can overcome that limitation by creating another ArrayList by copying values from this list using copy constructor as shown below. If you want to learn more about the Collection and ArrayList class, see Java Fundamentals: Collections course on Pluralsight, one of the specialized course on Collections.
And here is the complete Java program to show this in action: Arrays.asList() Example
import java.util.List;import java.util.Arrays; /** * How to create and initialize List in the same line, * Similar to Array in Java. * Arrays.asList() method is used to initialize a List * from Array but List returned by this method is a * fixed-size List and you can not change its size. * Which means adding and deleting elements from the * List is not allowed. * * @author Javin Paul */ public class ListExample { public static void main(String args[]) { //declaring and initializing array in one line String[] oldValues = new String[] {"list" , "set" , "map"}; String[] values = {"abc","bcd", "def"}; //initializing list with an array in java List init = Arrays.asList(values); System.out.println("size: " + init.size() +" list: " + init); //initializing List in one line in Java List oneLiner = Arrays.asList("one" , "two", "three"); System.out.println("size: " + init.size() +" list: " + oneLiner); // List returned by Arrays.asList is fixed size // and doesn't support add or remove // This will throw java.lang.UnsupportedOperationException oneLiner.add("four"); // This also throws java.lang.UnsupportedOperationException //oneLiner.remove("one"); } } Output:size: 3 list: [abc, bcd, def]size: 3 list: [one, two, three] Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:131) at java.util.AbstractList.add(AbstractList.java:91) at test.ExceptionTest.main(ExceptionTest.java:32) As shown in the above example it's important to remember that List returned by Arrays.asList() can not be used as a regular List for further adding or removing elements. It's kind of fixed length Lists which doesn't support the addition and removal of elements. Nevertheless its clean solution for creating and initializing List in Java in one line, quite useful for testing purposes. If you want to convert this fixed length List into a proper ArrayList, LinkedList or Vector any other Collection class you can always use the copy constructor provided by the Collection interface, which allows you to pass a collection while creating ArrayList or LinkedList and all elements from the source collection will be copied over to the new List. This will be the shallow copy so beware, any change made on an object will reflect in both the list. You can read more about shall and deep cloning in Java on The Complete Java Masterclass course on Udemy. One of my recommended course to all Java programmers. Here is also a summary of how to create a list with values in Java:
Arrays.asList() to ArrayList in Java
And, here is a sample Java program which will show you how you can convert this fixed-length list to ArrayList or LinkedList in Java: package beginner; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Java Program to create and initialize ArrayList LinkedList in same line * @author WINDOWS 8 */ public class HelloWorldApp { public static void main(String args[]) { List<String> pairs = Arrays.asList(new String[]{"USD/AUD", "USD/JPY", "USD/EURO"}); ArrayList<String> currencies = new ArrayList<>(pairs); LinkedList<String> fx = new LinkedList<>(pairs); System.out.println("fixed list: " + pairs); System.out.println("ArrayList: " + currencies); System.out.println("LinkedList: " + fx); } } Output: fixed list: [USD/AUD, USD/JPY, USD/EURO] ArrayList: [USD/AUD, USD/JPY, USD/EURO] LinkedList: [USD/AUD, USD/JPY, USD/EURO] That's all about how to declare and initialize a list with values in Java. This is pretty neat and I always this trick you create the Collection I want with values. You can use this to create ArrayList with values, Vector with values, or LinkedList with values. In theory, you can use this technique to create any Collection with values. Other ArrayList tutorials for Java Programmers- How to remove duplicate elements from ArrayList in Java? (tutorial)
- Top 5 courses to learn Java Collections and Streams (best courses)
- How to loop through an ArrayList in Java? (tutorial)
- 10 Advanced Core Java Courses for Programmers (advanced courses)
- How to synchronize an ArrayList in Java? (read)
- Top 5 Courses to become full-stack Java developers (online courses)
- How to create and initialize ArrayList in the same line? (example)
- Top 5 Java Concurrency and thread courses (best courses)
- When to use ArrayList over LinkedList in Java? (answer)
- Top 5 Courses to learn Spring MVC for beginners (spring courses)
- Difference between ArrayList and HashMap in Java? (answer)
- 10 Best Spring Boot Courses for Java developers (boot courses)
- Difference between ArrayList and Vector in Java? (answer)
- 10 Free Spring Courses for Java programmers (Free courses)
- How to sort an ArrayList in descending order in Java? (read)
- Difference between ArrayList and HashSet in Java? (answer)
- Difference between an Array and ArrayList in Java? (answer)
- How to reverse an ArrayList in Java? (example)
- How to get a sublist from ArrayList in Java? (example)
- How to convert CSV String to ArrayList in Java? (tutorial)
3 comments :
Sudhanshu said...If you are using Google Collections aka Google Guava, you can initialize any kind of ArrayList in one line e.g. Integer, String, Double, Float, Long or any arbitrary type. Google Collection provides a utility class Lists, which has several factory method to return ArrayList of any type e.g.List>Integer< listOfNumbers = Lists.newArrayList(1,2,3,4,5);
Anonymous said...The ArrayList returned by Arrays.asList() is not your regular list, its a fixed length arraylist where you cannot add or remove elements, though you can replace elements using set() mehtod. If you want to create a regular ArrayList, just use a copy constructor like below List mylist = new ArrayList((Arrays.asList(1,2 ,3,4));this will create a fixed length list of integers and then copy content to a new regualr arraylist
Anonymous said...Out of several ways, I think Arrays.asList() + Copy Constructor is best way to initialize ArrayList inline in Java.
Post a Comment
Newer Post Older Post Home Subscribe to: Post Comments ( Atom )Best System Design and Coding Interview Resources
System Design & Interview Prep
- ByteByteGo Lifetime Plan (50% OFF)
- Codemia Lifetime Plan (60% OFF)
- Exponent Annual Plan (70% OFF)
- Educative Premium Plus (55% OFF)
- DesignGurus All Course Bundle (55% OFF)
- Everything Java Interview Bundle (50% OFF)
- 101 Blockchain (50% OFF)
- Vlad Mihalcea's High Performance Bundle (50% OFF)
- Javarevisited Substack Subscription (50% OFF)
- Head First Software Architecture (Book)
Best Online Learning Resources and Platforms
- Coursera Plus Discount (40% OFF)
- Datacamp Discount (50% OFF)
- AlgoMonster Discount (50% OFF)
- Udemy Discount (80% OFF)
- Baeldung Discount (33% OFF)
- LabEx Discount (50% OFF)
- Codecademy Discount (50% OFF)
- Udacity Discount (50% OFF)
- ZTM Academy Discount (20% OFF)
- Frontend Masters Discount (10% OFF)
- Whizlabs Discount (30% OFF)
Search This Blog
Preparing for Java and Spring Boot Interview?
- Join My Newsletter .. Its FREE
My Books
- Everything Bundle (Java + Spring Boot + SQL Interview) for a discount
- Grokking the Java Interview
- Grokking the Spring Boot Interview
- Spring Framework Practice Questions
- Grokking the SQL Interview
- Grokking the Java Interview Part 2
- Grokking the Java SE 17 Developer Certification (1Z0-829 Exam)
My Courses
- Spring Professional Certification Practice Test
- Java SE 11 Certification Practice Test
- Azure Fundamentals AZ-900 Practice Test
- Java EE Developer Exam Practice Test
- Java Foundations 1Z0-811 Exam Practice Test
- AWS Cloud Practitioner CLF-C02 Exam Practice Test
- Java SE 17 1Z0-829 Exam Practice Test
- Azure AI-900 Exam Practice Test
- 1Z0-829 Java Certification Topic wise Practice Test
My Newsletter articles
- How to grow financially as Software Engineer?
- Difference between Microservices and Monolithic Architecture
- What is Rate Limiter? How does it work
- Difference between @Component vs @Bean annotations in Spring Framework?
- Top 10 Software Design Concepts Every Developer should know
- How does SSO Single Sign On Authentication Works?
Interview Questions
- core java interview question (183)
- interview questions (113)
- data structure and algorithm (99)
- Coding Interview Question (88)
- spring interview questions (52)
- design patterns (48)
- object oriented programming (42)
- SQL Interview Questions (37)
- thread interview questions (30)
- collections interview questions (26)
- database interview questions (16)
- servlet interview questions (15)
- hibernate interview questions (11)
- Programming interview question (6)
Java Tutorials
- FIX protocol tutorial (16)
- JDBC (35)
- Java Certification OCPJP SCJP (33)
- Java JSON tutorial (23)
- Java Programming Tutorials (21)
- Java multithreading Tutorials (64)
- Java xml tutorial (16)
- date and time tutorial (27)
- java IO tutorial (30)
- java collection tutorial (94)
- jsp-servlet (37)
- online resources (227)
Get New Blog Posts on Your Email
Get new posts by email:
SubscribeFollowers
Categories
- courses (348)
- SQL (80)
- linux (54)
- database (53)
- Eclipse (38)
- REST (34)
- Java Certification OCPJP SCJP (33)
- JVM Internals (27)
- JQuery (26)
- Testing (24)
- Maven (16)
- general (16)
Blog Archive
- ► 2026 (77)
- ► February (41)
- ► January (36)
- ► 2024 (185)
- ► December (14)
- ► November (3)
- ► October (35)
- ► September (28)
- ► August (10)
- ► July (20)
- ► June (7)
- ► May (24)
- ► April (30)
- ► March (9)
- ► February (1)
- ► January (4)
- ► 2023 (511)
- ► December (4)
- ► November (4)
- ► October (7)
- ► September (149)
- ► August (20)
- ► July (43)
- ► June (2)
- ► May (151)
- ► April (91)
- ► March (27)
- ► February (8)
- ► January (5)
- ► 2022 (69)
- ► December (1)
- ► September (1)
- ► August (20)
- ► July (20)
- ► June (7)
- ► May (5)
- ► April (4)
- ► March (3)
- ► February (6)
- ► January (2)
- ► 2021 (251)
- ► December (1)
- ► November (5)
- ► October (14)
- ► September (34)
- ► August (96)
- ► July (101)
Contributors
- SimpleJava
- javin paul
Popular Posts
-
I Joined 20+ Generative AI Online Courses — Here Are My Top 6 Recommendations for 2026 Hello guys, If you are following what's going on Tech then you may know that Generative AI has fundamentally changed the whole tech land...
-
How HashMap works in Java? Hello guys, if you are looking for an answer of popular Java interview question, how HashMap works in Java? or How HashMap works internally ...
-
How to create HTTP Server in Java - ServerSocket Example Java has very good networking support, allows you to write client-server applications by using TCP Sockets. In this tutorial, we will learn... -
The 2025 Java Developer RoadMap [UPDATED] Hello guys, I have been sharing a lot of roadmaps to become a Web developer , DevOps engineer , and recently React.js developer . One of th... -
Is ByteByteGo worth it in 2026 for System Design Interview Prep? Hello guys, when it comes to preparing for technical interviews, few challenges intimidate developers as much as system design . While cod...
-
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE I know how frustrating is to see "Exception in thread "main" java.lang.NoClassDefFoundError" while running your Java ...
-
DesignGurus.io or Bugfree.ai? Which is Better Place to Prepare for System Design Interview in 2026? Hello guys, preparing for coding interviews in 2026 is much more competitive than ever. The tech market is flooded with more qualified can...
-
Pluralsight vs CodeCademy Review 2025? Which is better to learn Programming and Development? As a programmer, the most important thing is to keep yourself up-to-date. If you don't, your skills will become obsolete, and you may n... -
Top 133 Java Interview Questions Answers for 2 to 5 Years Experienced Programmers Time is changing and so is Java interviews. Gone are the days, when knowing the difference between String and StringBuffer can help you to g... -
How to redirect a page or URL using JavaScript and JQuery - Example Redirecting a web page means, taking the user to a new location. Many websites uses redirects for many different reasons, e.g. Some websi...
Subscribe To
Pages
- Privacy Policy
- Terms & Conditions
Tag » How To Initialize A List In Java
-
Initializing A List In Java - GeeksforGeeks
-
Java List Initialization In One Line - Baeldung
-
How To Initialize List
Object In Java? - Stack Overflow -
How To Create, Initialize & Use List In Java - Software Testing Help
-
Initialize A List Of Lists In Java - Techie Delight
-
Initialize A List In Java In A Single Line With Specific Value
-
6 Ways To Initialize List Of String In Java
-
Java Program To Initialize A List - Tutorialspoint
-
How To Create And Initialize List Or ArrayList In One Line In Java ...
-
How To Initialize List In Java [Practical Examples] - GoLinuxCloud
-
Java: Initialize List With Zeroes - Programming.Guide
-
Initialize List Of String In Java - Java2Blog
-
Let's See, How To Teach Your Girlfriend 3 Ways To Initialize List In Java
-
Quickly Initialize A List With Elements & How To Print List - YouTube