Initialize the ArrayList in Java

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java generic collections allows you to have one type of object in collection i.e. you can create collection for String type or int type etc.

There are many ways to initialize the ArrayList as given below. Let’s learn them one by one.

1) Initialize with a particular type in angular braces:

Syntax: 

Example:

All Bank Names: [ICICI, HDFC, SBI]

2) Initialization using Arrays.asList:

Syntax:

Example:

All Bank Names: [ICICI, HDFC, SBI]

3) Initialize using anonymous inner class method:

Syntax:

Example:

All Bank Names: [ICICI, HDFC, SBI]

4) Using Collections.ncopies :

This method can be used when we need to initialize the same values for all of its elements.

Arguments:
Count: 
Number of elements
Element: The item value which needs to be stored

Syntax:

Example:

All Bank Names: [ICICI, HDFC, SBI]
Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

Print Friendly, PDF & Email
ArrayList in Java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. Anil says:

    What exactly does Collection. ncopies do ?is the output correct for this example?
    public class ArrayLIstEx {

    public static void main(String args[]){

    ArrayList itemlist = new ArrayList(Collections.nCopies(10, 2));

    System.out.println(“All Items : “+itemlist);
    }
    }

    this is what i am asking about : All Bank Names: [ICICI, HDFC, SBI]

Leave a Reply

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