beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to initialize an ArrayList

By Chaitanya Singh | Filed Under: Java Collections

In the last post we discussed about class ArrayList in Java and it’s important methods. Here we are sharing multiple ways to initialize an ArrayList with examples.

Method 1: Initialization using Arrays.asList

Syntax:

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

Example:

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]

Method 2: Anonymous inner class method to initialize ArrayList

Syntax:

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

Example:

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

Output:

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

Method3: Normal way of ArrayList initialization

Syntax:

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

Example:

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]

Method 4: Use Collections.ncopies

Collections.ncopies method can be used when we need to initialize the ArrayList with the same value for all of its elements. Syntax: count is number of elements and element is the item value

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

Example:

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]

Enjoyed this post? Try these related posts

  1. Difference between List and Set in Java
  2. Hashtable in java with example
  3. How to sort ArrayList in descending order in Java
  4. Java – Remove all mappings from HashMap example
  5. Java – LinkedList Iterator example
  6. Remove mapping from Hashtable example – Java

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
    • tony says

      August 1, 2015 at 3:41 AM

      Hello Nysa,
      I don’t know if you received an answer to your question. I’m a beginner as well learning Java. I believe you received that error message because you are using a later version of Java than the one the author posted here. If you look at the web address, it looks like he created this page in 2013. I have seen certain commands are different in my school book than what I find on the web, and I believe the version is the reason.
      Hope this helps. Even if you do not get this, others may run into this same issue and find my comment helpful.

      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 Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap