Collections

Java ArrayList add method example

Java ArrayList add method example shows how to add elements to ArrayList in Java. Java ArrayList add method example also shows how to add elements at specified index of ArrayList.

How to add elements to Java ArrayList?

Java ArrayList class provides add method which can be used to add elements to it.

This method adds specified element at the end of the ArrayList.

Example

Output

Also check out how to print ArrayList example.

How to add element at specified index of the ArrayList?

By default add method inserts element at the end of the ArrayList. If you want to add element at specified index of the ArrayList, you can use overloaded add method which also takes index parameter.

This method inserts the element at the specified index of the ArrayList. It shifts existing element at the specified index and any subsequent elements to the right by adding 1 to their indices.

Example

Output

Make sure to always specify the type of ArrayList. Consider below given code.

Do you think it will compile? If your answer is no, you are wrong. It will compile since we did not declare type along with the ArrayList, it will be considered as ArrayList of objects. The value 1 will be autoboxed to Integer and added to ArrayList. Disadvantage is, when you get elements from such ArrayList, you will have to explicitly cast the values to appropriate type.

How to add ArrayList to ArrayList?

Just like any other object. See below given example.

Output

How to add all elements of ArrayList to another ArrayList?

Use addAll method to add all elements of one ArrayList to another ArrayList.

Example

Output

Elements of other ArrayList will be added at the end of the first ArrayList. If you want to add elements at specified index, you can use overloaded addAll method which also accepts index. Also checkout how to copy elements of one ArrayList to another ArrayList example.

Reference: ArrayList JavaDoc (Java 8)

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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