BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to Initialize an ArrayList

By Chaitanya Singh | Filed Under: java

In this tutorial, you will learn multiple ways to initialize an ArrayList.

1. ArrayList Initialization using Arrays.asList() method

The asList() method of Arrays class converts an array to ArrayList. This is a perfect way to initialize an ArrayList because you can specify all the elements inside asList() method.

Syntax:

ArrayList<Type> obj = new ArrayList<Type>(
        Arrays.asList(Object o1, Object o2, Object o3, ....so on));

Example:
Here, we have initialized an ArrayList of string type using Arrays.asList() method. We have specified three string elements inside asList(), these elements are added as arraylist elements. As you can see, when we print the arraylist elements, it prints the three strings that we passed inside asList().

import java.util.*;
public class InitializationExample1 {
   public static void main(String args[]) {
     ArrayList<String> obj = new ArrayList<String>(
		Arrays.asList("Pratap", "Peter", "Harsh"));
     System.out.println("Elements are:"+obj);
   }
}

Output:

Elements are:[Pratap, Peter, Harsh]

Another example: Using Arrays.asList() to initialize an ArrayList of integer type.

import java.util.*;
public class JavaExample {
  public static void main(String args[]) {
    ArrayList<Integer> numbers = new ArrayList<Integer>(
            Arrays.asList(10, 20, 30, 40, 50));
    System.out.println("ArrayList elements are: "+numbers);
  }
}

Output:

ArrayList elements are: [10, 20, 30, 40, 50]

2. Anonymous inner class method to initialize an ArrayList

Here, we initialize an ArrayList using anonymous inner class. Note the double curly braces. The elements are specified using add().
Syntax:

ArrayList<T> obj = new ArrayList<T>(){{
		   add(Object o1);
		   add(Object o2);
		   add(Object o3);
                   ...
                   ...
		   }};

Example:

import java.util.*;
public class JavaExample {
  public static void main(String args[]) {
    ArrayList<String> cities = new ArrayList<>(){{
      add("Delhi");
      add("Agra");
      add("Chennai");
      add("Pune");
      add("Noida");
    }};
    System.out.println("Content of Array list cities:"+cities);
  }
}

Output:

Content of Array list cities:[Delhi, Agra, Chennai, Pune, Noida]

3. Normal way of ArrayList initialization

This is the most common and frequently used method of initializing an array. Here we are using add() method of ArrayList class to add elements to an ArrayList.

Syntax:

ArrayList<T> obj = new ArrayList<T>();
	   obj.add("Object o1");
	   obj.add("Object o2");
	   obj.add("Object o3");
                        ...
                        ...

Example:
In the following example, we have created an ArrayList with the name books. We can add as many elements as we want by calling add() method. Please keep in mind the type of the ArrayList. In this example, we have created an arraylist of string type so we are specifying strings in add() method. If the arraylist is of integer type, you need to specify the numbers in add() method else the program will throw compilation error.

import java.util.*;
public class Details {
   public static void main(String args[]) {
     ArrayList<String> books = new ArrayList<String>();
     books.add("Java Book1");
     books.add("Java Book2");
     books.add("Java Book3");
     System.out.println("Books stored in array list are: "+books);
   }
}

Output:

Books stored in array list are: [Java Book1, Java Book2, Java Book3]

4. Initializing an ArrayList with multiple same elements using Collections.ncopies()

Collections.ncopies() method is used, when we need to initialize the ArrayList with multiple same elements. For example, if you want an ArrayList with 50 elements and all elements as 10 then you can call the method like this: = new ArrayList<Integer>(Collections.nCopies(50, 10))

Syntax:

ArrayList<T> obj = new ArrayList<T>(Collections.nCopies(count, element));

count is number of elements and element is the item value

Example:
In the following example, we have initialized an array with 10 elements and all the elements are 5.

import java.util.*;
public class Details {
   public static void main(String args[]) {
     ArrayList<Integer> intlist = new ArrayList<Integer>(Collections.nCopies(10, 5));
     System.out.println("ArrayList items: "+intlist);
   }
}

Output:

ArrayList items: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

Recommended articles:

  • Sort ArrayList in Java
  • ArrayList vs LinkedList
❮ Java ArrayListJava Collections ❯

Comments

  1. Nysa says

    February 27, 2015 at 7:51 PM

    Hi i used the anonymous inner class way to initialize an arrayList but i get the error below:

    The type java.util.function.Consumer cannot be resolved. It is indirectly referenced from required .class files

    Can you hint me as to what i have missed ?

    Thanks
    Nysa

    Reply
    • irfan says

      July 17, 2017 at 4:42 PM

      may be u are missing import statement

      Reply
  2. Shivam says

    July 31, 2015 at 3:07 PM

    Hello,

    I have a doubt :
    //************************************

    import java.util.*;

    public class Initialization2 {

    public static void main(String args[]) {
    final ArrayList cities = new ArrayList() {

    {
    add(“Delhi”);
    add(“Agra”);
    add(“Chennai”);
    }
    };
    System.out.println(“Content of Array list cities:” + cities);
    cities.add(“Goa”);
    System.out.println(“Content of Array list cities:” + cities);
    }
    }

    //************************************

    In this code I have declared the ArrayList as “final” so it should not allow any modifications, like any integer variable marked as final cannot be changed once it is assigned.
    But it allows the modification as I have added one more object “Goa” to cities ArrayList.

    Please explain.
    Thanks

    Reply
    • vishwjeet says

      December 18, 2015 at 10:41 AM

      @Shivam in the above example…u r making reference variable as final so,if u want to again assign reference variable cities= new ArrayList();// you will get warning

      Reply
  3. Shashibhushan says

    August 13, 2015 at 5:20 AM

    In the example 1 to initialize , you missed showing the relationship between the arrays.aslist and arraylist object…

    arr.addAll(Arrays.asList(“bangalore”,”hyderabad”,”chennai”));

    Reply
  4. Aditya says

    July 6, 2017 at 6:50 AM

    In this method,
    ArrayList cities = new ArrayList(){{
    add(“Delhi”);
    add(“Agra”);
    add(“Chennai”);
    }};

    Why is there 2 openings after object creation I didn’t get that and what is the difference between ArrayList and Array.asList.
    In the above example what I have given why not use “cities.add(“”) ” and whats the difference between add and obj.add ?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap