How To Declare And Initialize A List With Values In Java (ArrayList ...

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. How to create and initialize List in one line in Java with Array 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: How to declare and initialize a List in one line

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)
Thanks for reading this article so far. If you like this article then, please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. P.S, - If you are new to the Java world and looking to self-teach Java to yourself, here is a list of some Free Java courses for Beginners from Udemy, Coursera, and Pluralsight you can join to learn Java online.

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);

March 11, 2013 at 7:43 PM 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

September 29, 2015 at 1:50 AM Anonymous said...

Out of several ways, I think Arrays.asList() + Copy Constructor is best way to initialize ArrayList inline in Java.

June 8, 2016 at 11:30 PM

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:
Subscribe

Followers

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

  • ▼  2025 (910)
    • ▼  June (106)
      • How to sort an Array in Java? Ascending and Descen...
      • How to loop through an Array in Java? Example Tuto...
      • How to declare and initialize a List with values i...
      • How to implement Skip List in Java? Example Tutorial
      • How to find If Linked List Contains Loop or Cycle ...
      • How to use Array in Java? Example Tutorial
      • Top 15 Data Structures and Algorithm Interview Que...
      • Difference between Stable and Unstable Sorting Alg...
      • How to Count Number of Leaf Nodes in a Binary Tree...
      • 6 ways to declare and initialize a two-dimensional...
      • How to implement Bucket Sort in Java? [Solved] - E...
      • Recursive Binary Search Algorithm in Java - Exampl...
      • Difference between Stack and Queue Data Structure ...
      • Difference between Comparison (QuickSort) and Non-...
      • How to implement Post Order Traversal of Binary Tr...
      • How to Implement Binary Search Tree in Java? Example
      • How to Compare Arrays in Java – Equals vs deepEqua...
      • Recursion in Java with Example – Programming Tutor...
      • 3 Examples to Print Array Elements/Values in Java ...
      • Iterative QuickSort Example in Java - without Recu...
      • 4 Ways to Search Java Array to Find an Element or ...
      • How to loop over two dimensional array in Java? Ex...
      • 2 Examples to Convert Byte[] Array to String in Java
      • How to Fix Exception in thread "main" java.lang.Ar...
      • How to remove all special characters from String i...
      • StringTokenizer Example in Java with Multiple Deli...
      • How to replace a substring in Java? String replace...
      • How to check if String contains another SubString ...
      • How to check if a String is numeric in Java? Use i...
      • How to split String in Java by WhiteSpace or tabs?...
      • Java String Replace Example Tutorial
      • How SubString method works in Java - Memory Leak F...
      • How to use String in switch case in Java with Example
      • How to String Split Example in Java - Tutorial
      • How to convert String or char to ASCII values in J...
      • How to format String in Java – String format Example
      • How String in Switch works in Java? Example
      • 10 Things Every Java Programmer Should Know about ...
      • How to Split String based on delimiter in Java? Ex...
      • String replaceAll() example - How to replace all c...
      • Why character array is better than String for Stor...
      • How to Compare Two Strings Without Case Sensitivit...
      • 2 Ways to remove whitespaces from String in Java? ...
      • Difference in String pool between Java 6 and 7? An...
      • 10 Difference between StringBuffer and StringBuild...
      • How to Convert and Print Byte array to Hex String ...
      • StringJoiner.join() and String.join() Example in J...
      • 3 ways to convert String to Boolean in Java? Examples
      • Top 15 Java String interview Question Answers for ...
      • How to compare two String in Java - String Compari...
      • How to Remove First and Last Character of String i...
      • How to get first and last character of String in J...
      • How to check if String is not null and empty in Ja...
      • When to use intern() method of String in Java? Exa...
      • How to split a comma separated String in Java? Reg...
      • Why String is Immutable or Final in Java? Explained
      • How to Convert an Array to Comma Separated String ...
      • Top 10 Low Latency Tips for Experienced Java Devel...
      • Difference between Stack and Heap memory in Java? ...
      • What is load-on-startup servlet element in web.xml...
      • Difference between SendRedirect() and Forward() in...
      • Difference between throw and throws in Exception h...
      • Difference between Struts 1 and Struts 2 Web Devel...
      • 10 points on finalize method in Java – Tutorial Ex...
      • What is Static and Dynamic binding in Java with Ex...
      • 3 Examples to Concatenate String in Java
      • 3 Ways to Convert an Array to ArrayList in Java? E...
      • How to Replace Line Breaks , New Lines From String...
      • How to Convert Byte Array to InputStream and Outpu...
      • How to Convert InputStream to Byte Array in Java -...
      • How to Reverse Array in Place in Java? Solution Wi...
      • How to Convert List of Integers to Int Array in Ja...
      • How to Generate MD5 Hash in Java - String Byte Arr...
      • Top 5 Courses to Learn JIRA for Beginners and Expe...
      • Is IBM Data Analyst Professional Certificate on Co...
      • Top 5 Courses to Learn Visual Studio Code IDE for ...
      • Top 10 Edureka Courses & Certifications for Java a...
      • Top 10 Free AWS Courses on Udemy For Beginners in ...
      • Top 10 Free Eclipse and IntelliJ IDEA Courses for ...
      • 10 Free TypeScript Courses for Beginners in 2025
      • Top 5 Free Courses To Learn Terraform in 2025 - Be...
      • 7 Free CI/CD and Jenkins Courses for Java Programm...
      • Top 6 Courses to Learn Data Structures and Algorit...
      • Top 5 Online Courses to Learn Ethical Hacking in 2...
      • 7 Best Free Datacamp Courses to Learn Online in 20...
      • Top 5 CompTIA Server+ Certification Exam Courses a...
      • Google Protocol Buffers (ProtoBuf) - Best Alterna...
      • Student Management System Project - FullStack Java...
      • 10 Programming Best Practices to Name Variables, M...
      • 10 Tips to Learn a New Project or Codebase Quickly
      • 10 Things to Remember while doing Database Server ...
      • Difference between Inheritance and Composition in ...
      • Why use Cloud Computing? Advantages and Disadvantages
      • 10 Tips to create Maintainable Java Applications
      • Why Static Code Analysis is Important? Pros and Cons
      • Top 23 Design Patterns Experienced Java Programmer...
      • Top 5 Cloud Computing Platforms Java Programmers S...
      • How Long does It take To Learn Linux?
      • Top 10 Most Popular Programming Languages of the L...
      • Top 10 Excuses Programmers Gives to Avoid Unit Tes...

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

Posts Atom Posts Comments Atom Comments

Pages

  • Privacy Policy
  • Terms & Conditions
Copyright by Javin Paul 2010-2025. Powered by Blogger.

Tag » How To Initialize A List In Java