Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Creating ArrayLists
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Now that we have entered the world of arrays, let's talk about the ArrayList class in Java and what it offers in addition to the known capabilities of arrays. An ArrayList object contains an array of object references as well as methods for managing the array. The elements of an ArrayList must be object references, not primitive data such as int or double. Take a look at the ArrayList of String values as an example. The ArrayList class has to be imported from the java.util package in order for the program to compile without error.
ArrayListsExample.java
package exlcode;
import java.util.ArrayList;
public class ArrayListsExample {
public static ArrayList exampleVariableOne = new ArrayList();
public static ArrayList exampleVariableTwo = new ArrayList(5);
public static void main(String[] args) {
// "add" will be explained later this unit
exampleVariableOne.add("Hello");
exampleVariableOne.add("World");
// ArrayLists can be printed directly to the console, unlike arrays
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}
The syntax for declaring an ArrayList is:
ArrayList<objectType> name = new ArrayList<objectType>();.
By default, an ArrayList will start out with 10 empty cells. If you want to start with an initial capacity, put a number in the parentheses. This does not limit the size the ArrayList can expand to. A benefit of an ArrayList is that elements may continue to be added regardless of the original size of the ArrayList. The size of the ArrayList will automatically increase and no information will be lost.