Skip to content

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 the specified index of ArrayList.

Java ArrayList is a part of the Java Collection framework.

How to add elements to Java ArrayList using the add method?

Java ArrayList add method which can be used to adds elements to the ArrayList object.

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

Example

Output

Also, check out how to print ArrayList example.

How to add an element at the specified index of the ArrayList?

By default add method inserts element at the end of the ArrayList. If you want to add element at the specified index of the ArrayList, you can use the overloaded add method which also takes an 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. The disadvantage is, when you get elements from such an ArrayList, you will have to explicitly cast the values to the 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 the specified index, you can use the overloaded addAll method which also accepts an index. Also, check out how to copy elements of one ArrayList to another ArrayList example.

This example is a part of the Java ArrayList tutorial with examples.

Reference: ArrayList JavaDoc (Java 8)

About the author

Leave a Reply

Your email address will not be published.