Arraylist java: Explanation to declare, initialize and print it with code example

Arraylist is included in the Java Collections Framework. Similar to arrays, it allows you to remove or add elements in any time, or dynamically. In this guideline, we will deliver you more information 2d Arraylist java, how to declare, initialize and print it

2d arraylist java

Here is the hierarchy of arraylist java. The Arraylist will implement the List interface. Then, this will extend from the collection interface

2d arraylist java

Different from the Arrays that fixed in size, 2d Arraylist Java will automatically increase its size whenever a new element is added

When it comes to 2d Arraylist Java, here are something you should remember

  • Arraylist’s resizable to fit with the added or removed elements. 
  • 2d Arraylist Java uses arrays to store elements. As a result, you can retrieve those elements by their indexes 
  • You can duplicate and null values with 2d Arraylist Java
  • It is an ordered collection, therefore it keeps the insertion order of elements
  • One of the most important factors that differentiate 2d Arraylist Java from Vector class of Java is that Arraylist Java is not synchronized. Then, you need to explicitly synchronize access to an Arraylist if multiple threads modify it
  • Moreover, Arraylist is more identical to Vectors in C++
  • If you want to remove any elements from the Arraylist Java, you might need to do a lot of shifting of elements. As a result, the operations utilize elements in the Arraylist will be very slow
  • 2a Arraylist Java class can only contain objects. Therefore, sometimes it’s called “ Arraylist of objects”. Then, in case you want to store integer type of elements, you’ll need to use integer objects of the wrapper class and not primitive type int

How to create and declare 2d arraylist java

First, we’ll come to the default constructor. In this process, you’ll have to add in the Arraylist class to your program. You can carry out this step with “ import” directive below

import java.util.ArrayList;

OR

import java.util.*; //

After this, you can create an Arraylist objects

Besides the default constructor, there are many overloaded constructors for you to create the Arraylist. Let’s list down some of the constructor methods

2d Arraylist Java constructor methods

Arraylist()

This method use the default constructor to create an empty Arraylist

Here is the syntax of this method

ArrayList<data_type> list_name = new ArrayList<>();

Data type is the type of your data, “String” for example. Also, list_name is the name of your Arraylist

Arraylist (int capacity)

If you want to create a 2d Arraylist Java with specific size or capacity, you should use Arraylist (int capacity) 

General syntax for this is

ArrayList<data_type> list_name = new ArrayList<>(int capacity);

For instance, you want to create a new Arraylist named “ Arraylist”, type “string” with a capacity of 15. Then, here will be your syntax

ArrayList<String> arraylist = new ArrayList<>(15);

Arraylist ( Collection<? Extends E> c)

Different from the above two methods, this 2d Arraylist method uses an existing collection as an argument. Therefore, while two methods above create an empty Arryalist, this method can make an Arraylist with elements 

General syntax for this

ArrayList<data_type> list_name = new ArrayList<> (Collection c)

Initialize 2d Arraylist Java 

Now, you’ve created the ArrayList. Then, it’s time for you to initialize it with values. Here are some methods for you

Use Arrays.asList

With Arrays.asList method, you can pass an Array converted to List to initialize 2d Arraylist Java

General Syntax 

ArrayList<data_type> arrayListName = new ArrayList<data_type>(

            Arrays.asList (Object o1, Object o2, …, Object on));

To illustrate, we deliver you an example

import java.util.*;

public class Main {

   public static void main(String args[]) {

     ArrayList<Integer> Arraylist = new ArrayList<Integer>(

     Arrays.asList(“A”, “B”, “C”));

       System.out.println(“List contents:”+Arraylist);

    }

}

Output  

List contents: [ A, B, C]

Anonymous inner class method

General syntax of this method

ArrayList<data_type>arraylistName = new ArrayList<data_type>(){{

add(Object o1); add (Object o2);…

add (Object on);}};

For instance

import java.util.*;

public class Main {

   public static void main(String args[]) {

       ArrayList<String> numbers = new ArrayList<String>(){{

        add(“One”);

        add(“Two”);

        add(“Three”);

           }};

    System.out.println(“Content of ArrayList:”+numbers);

   }

}

 Output

Content of ArrayList: [ One, Two, Three]

Add method

Suggests in the name, this method is common for adding elements to any collection

General syntax

ArrayList<data_type>ArraylistName = new ArrayList<data_type>();

ArraylistName.add(value1);

ArraylistName.add(value2);

ArraylistName.add(value3);

For example,

import java.util.*;

public class Main {

   public static void main(String args[]) {

             ArrayList<String> numbers = new ArrayList<String>();

       numbers.add(“One”);

       numbers.add(“Two”);

       numbers.add(“Three”);

       numbers.add(“Four”);

       System.out.println(“Content of ArrayList:”+numbers);

     }

}

Output

Content of Arraylist: [ One, Two, Three, Four]

Collection.nCopies Method

With this method, you can initialize the ArrayList with the similar values. Then, here is its general syntax

ArrayList<data_type> arrayListName = new

ArrayList<data_type>(Collections.nCopies(count, element));

Now, let’s consider this example. For example, we want to create Arraylist with 10 elements and initialize to value 10.

import java.util.*;

public class Main {

   public static void main(String args[]) {

         ArrayList<String> List = new ArrayList<String>(Collections.nCopies(10,10));

        System.out.println(“Content of ArrayList:”+List);

   }

}

Iterate through 2d Arraylist Java

In this guideline, we’ll deliver you 5 main ways to traverse through or loop through the ArrayList. Let’s dive right in

Using for loop

You can use an index – based for loop. Then, you can traverse the Arraylist and print its elements. This might be one of the easiest way to traverse and print Arraylist’s elements

We use this example to illustrate this method

import java.util.*;

public class Main

{

    public static void main(String[ ] args) {

        List<String> List  = new ArrayList<>();

        intList.add(15);

        intList.add(25);

        intList.add(35);

        intList.add(45);

        intList.add(55);

         ArrayList<String> arraylist = new ArrayList<>(List);

        System.out.println(“Contents of ArrayList using for-loop:”);

        for(int i=0;i<List.size();i++){

               System.out.print(intList.get(i) + ” “);

        }

    }

Output

Contents of Arraylist using for – loop: 15   25   35   45    55

By for – each loop

The following program will show you how to traverse and loop through ArrayList using for – each loop

import java.util.*;

public class Main

{

    public static void main(String[] args) {

        List<String> ArrayList  = new AList<>();

        AList.add(10);

        AList.add(20);

        AList.add(30);

        AList.add(40);

        AList.add(50);

        AList<String> arraylist = new ArrayList<>(AList);

        System.out.println(“Contents of ArrayList using for-each loop:”);

        intList.forEach(val ->{

       System.out.print(val + ” “);

        });

      }

}

Output:

Contents of Arraylist using for each loop: 10   20   30   40    50

Use iterator Interface

Iterator interface will help you iterate through the 2d Arraylist and print its value

Here’s how to do it

import java.util.*;

public class Main

{

    public static void main(String[] args) {

        List<String> AList  = new ArrayList<>();

        AList.add(5);

        AList.add(15);

        AList.add(25);

        AList.add(35);

        AList.add(45);

        //create & initialize a new ArrayList with previous list

        ArrayList<String> arraylist = new ArrayList<>(AList);

       System.out.println(“Contents of ArrayList using Iterator interface:”);

     //Traverse through the ArrayList using iterator

    Iterator iter=arraylist.iterator(); 

       while(iter.hasNext()){ 

            System.out.print(iter.next() + ” “); 

       } 

       }

}

Output 

Contents of ArrayList using Iterator Interface: 5    15    25    35   45

ListIterator Interface

With ListIterator interface, you can traverse in backward as well as forward direction

Example

import java.util.*; 

class Main{ 

  public static void main(String args[]){ 

    List<Integer> letters_list=new ArrayList<Integer>();

    Letters_list.add(“A”); 

    Letters_list.add(“B”); 

    Letters_list.add(“C”); 

    Letters_list.add(“D”);

    Letters_list.add(“E”);

    Letters_list.add(“F”);

    System.out.println(“The contents of the list using ListIterator:”);

      ListIterator<Integer> letter_iter=letters_list.listIterator(letters_list.size()); 

      while(letter_iter.hasPrevious()) 

        { 

            String str=color_iter.previous(); 

            System.out.print(str + ” “); 

        }

 } 

Output

The content of list using ListIterator

A   B   C   D   E   F

By forEachRemaining () Method

Let’s consider this example

import java.util.*; 

class Main{ 

  public static void main(String args[]){ 

    List<Integer> letters_list=new ArrayList<Integer>(); 

    letters_list.add(“A”); 

    letters_list.add(“B”); 

    letters_list.add(“C”); 

    letters_list.add(“D”);

    letters_list.add(“E”);

    letters_list.add(“F”);

    System.out.println(“The contents of the list using forEachRemaining() method:”);

       Iterator<Integer> itr=letters_list.iterator(); 

        itr.forEachRemaining(val-> //lambda expression 

          { 

            System.out.print(val + ” “); 

          }); 

 } 

Output:

The contents of the list using forEachRemaining() method:

A    B    C    D    E    F

In conclusion

We hope to deliver you some valid and sufficient understanding about 2d Arraylist Java. However, in case you still meet some problems and issues when working with it, then you should contact ArrowHitech

Having more than 12 year – experience, we surely can deliver you the best help with the Arraylist Java. Working with our decade – long experience developers, you definitely can handle all the process easily. Moreover, we also work on eCommerce platforms like Magento, Shopify or WordPress. Then, if you want to open your online store, ArrowHitech will be a great partner.

What are you waiting for? Contact us here or via email: support@arrowhitech.com or hotline + 84 243 7955 813

Tags

Share