Can you initialize ArrayList with values?

The Java ArrayList can be initialized in number of ways depending on the requirement. In this tutorial, we will learn to initialize ArrayList based on some frequently seen usecases.

Table of Contents 1. Initialize ArrayList in single line 2. Create ArrayList and add objects 3. Initialize arraylist of lists

1. Initialize ArrayList in one line

1.1. Arrays.asList[] – Initialize arraylist from array

To initialize an arraylist in single line statement, get all elements in form of array using Arrays.asList method and pass the array argument to ArrayList constructor.

ArrayList names = new ArrayList[ Arrays.asList["alex", "brian", "charles"] ]; System.out.println[names];

Program output.

[alex, brian, charles]

1.2. List.of[] – Immutable list – Java 9

We can use List.of[] static factory methods to create immutable lists. Only drawback is that add operation is not supported in these lists.

List names = List.of["alex", "brian"]; System.out.println[names];

Program output.

[alex, brian]

Read More : Java 9 Immutable Collections

2. Create ArrayList and add objects – ArrayList constructor

Using ArrayList constructor is traditional approach. We create a blank arraylist using constructor and add elements to list using add[] method. We can add elements either one by one, or we can pass another collection to add all elements in one step.

ArrayList names = new ArrayList[]; //1. Add elements one by one names.add["alex"]; names.add["brian"]; names.add["charles"]; System.out.println[names]; HashMap details = new HashMap[]; details.put["keanu", 23]; details.put["max", 24]; details.put["john", 53]; //2. Add elements from other collection names.addAll[details.keySet[]]; System.out.println[names];

Program output.

[alex, brian, charles] [alex, brian, charles, max, john, keanu]

3. Initialize arraylist of lists

At times, we may need to initialize arraylist of lists.

List marks = new ArrayList[]; marks.add[ Arrays.asList[10, 20, 30] ]; marks.add[ Arrays.asList[40, 50, 60] ]; marks.add[ Arrays.asList[70, 80, 90] ]; for [List mark : marks] { System.out.println[mark]; }

Program output.

[10, 20, 30] [40, 50, 60] [70, 80, 90]

Please note that Arrays.asList[] does not return java.util.ArrayList instance. It returns java.util.Arrays$ArrayList instance instead.

So if you must have an ArrayList only, then create ArrayList for Arrays.asList[] instance in below manner.

marks.add[new ArrayList[ Arrays.asList[10, 20, 30] ]];

That’s all about to create an arraylist in Java. Drop me your questions in comments.

Happy Learning !!

Reference:

ArrayList Java Docs
A Guide to Java ArrayList

Let us know if you liked the post. That’s the only way we can improve.

In this article, we will learn to initialize ArrayList with values in Java.
ArrayList is an implementation class of List interface in Java. It is used to store elements. It is based on a dynamic array concept that grows accordingly. We can Initialize ArrayList with values in several ways. Let’s see some of them with examples.

Many careers in tech pay over $100,000 per year. With help from Career Karma, you can find a training program that meets your needs and will set you up for a long-term, well-paid career in tech.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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 obj = new ArrayList[ Arrays.asList[Object o1, Object o2, Object o3, ....so on]];

Example:

import java.util.*; public class InitializationExample1 { public static void main[String args[]] { ArrayList obj = new ArrayList[ 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 obj = new ArrayList[]{{ add[Object o1]; add[Object o2]; add[Object o3]; ... ... }};

Example:

import java.util.*; public class InitializationExample2 { public static void main[String args[]] { ArrayList cities = new ArrayList[]{{ 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 obj = new ArrayList[]; 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 books = new ArrayList[]; 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 obj = new ArrayList[Collections.nCopies[count, element]];

Example:

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

Output:

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

ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

  • ArrayList inherits AbstractList class and implements List interface.
  • ArrayList is initialized by a size, however the size can increase if collection grows or shrink if objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases [see this for details].
  • ArrayList in Java can be seen as similar to vector in C++.

Below are the various methods to initialize an ArrayList in Java:

  1. Syntax:

    ArrayList str = new ArrayList[]; str.add["Geeks"]; str.add["for"]; str.add["Geeks"];

    Examples:

    import java.util.*;

    public class GFG {

        public static void main[String args[]]

        {

            ArrayList gfg = new ArrayList[];

            gfg.add["Geeks"];

            gfg.add["for"];

            gfg.add["Geeks"];

            System.out.println["ArrayList : " + gfg];

        }

    }

    Output:ArrayList : [Geeks, for, Geeks]

    Examples: Using shorthand version of this method

    import java.util.*;

    public class GFG {

        public static void main[String args[]]

        {

            ArrayList gfg = new ArrayList[] {

                {

                    add["Geeks"];

                    add["for"];

                    add["Geeks"];

                }

            };

            System.out.println["ArrayList : " + gfg];

        }

    }

    Output:ArrayList : [Geeks, for, Geeks]

  2. Syntax:

    ArrayList obj = new ArrayList[ Arrays.asList[Obj A, Obj B, Obj C, ....so on]];

    Examples:

    import java.util.*;

    public class GFG {

        public static void main[String args[]]

        {

            ArrayList gfg = new ArrayList[

                Arrays.asList["Geeks",

                              "for",

                              "Geeks"]];

            System.out.println["ArrayList : " + gfg];

        }

    }

    Output:ArrayList : [Geeks, for, Geeks]

  3. Syntax:

    List obj = new ArrayList[ List.of[Obj A, Obj B, Obj C, ....so on]];

    Examples:

    import java.util.*;

    public class GFG {

        public static void main[String args[]]

        {

            List gfg = new ArrayList[

                List.of["Geeks",

                        "for",

                        "Geeks"]];

            System.out.println["ArrayList : " + gfg];

        }

    }

    Output:ArrayList : [Geeks, for, Geeks]

  4. Syntax:

    List gfg = new ArrayList[collection];

    Examples:

    import java.util.*;

    public class GFG {

        public static void main[String args[]]

        {

            List arr = new ArrayList[];

            arr.add[1];

            arr.add[2];

            arr.add[3];

            arr.add[4];

            arr.add[5];

            List gfg = new ArrayList[arr];

            System.out.println["ArrayList : " + gfg];

        }

    }

    Output:ArrayList : [1, 2, 3, 4, 5]


Video liên quan

Chủ Đề