Member-only story
Java Programming Language: How to Add Elements Into an ArrayList
Hi everyone, welcome back. In this example, we will be going over how to add elements into arraylists in Java. Arraylists can be used to store a collection of data, similar to that of an array. The key difference between an arraylist and an array is that an arraylist is resizable whereas an array is not. This leaves the arraylist as a great choice when wanting to modify a collection of data. With this introduction out of the way, let’s get into it.
Creating ArrayList
Let’s start by creating an arraylist. Before we can create the arraylist, we need to make sure we have our arraylist import, which is included within the java.util package:
import java.util.ArrayList;
Now, we can successfully create our arraylist:
ArrayList<Integer> myArrList = new ArrayList<Integer>();
We have created an arraylist variable of the integer data type.
Adding Elements Into The ArrayList
Now, let’s try to add elements into our arraylist. We can do this by using the built in add() function that is provided. Let’s see an example:
ArrayList<Integer> myArrList = new ArrayList<Integer>();
myArrList.add(1);
myArrList.add(2)…