How to Create ArrayList in Java: Syntax and Examples
To create an
ArrayList in Java, first import java.util.ArrayList. Then declare and initialize it using ArrayList<Type> list = new ArrayList<>();, where Type is the type of elements you want to store.Syntax
Here is the basic syntax to create an ArrayList in Java:
- ArrayList<Type>: Declares an ArrayList that holds elements of the specified
Type. - list: The variable name for your ArrayList.
- new ArrayList<>(): Creates a new empty ArrayList instance.
java
import java.util.ArrayList; ArrayList<Type> list = new ArrayList<>();
Example
This example shows how to create an ArrayList of strings, add some items, and print them.
java
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); for (String fruit : fruits) { System.out.println(fruit); } } }
Output
Apple
Banana
Cherry
Common Pitfalls
Common mistakes when creating or using ArrayLists include:
- Forgetting to import
java.util.ArrayList. - Not specifying the type inside angle brackets, which can cause warnings or errors.
- Trying to use primitive types like
intdirectly instead of wrapper classes likeInteger. - Using raw types (e.g.,
ArrayList list = new ArrayList();) which is discouraged.
java
/* Wrong way: Missing import and raw type usage */ // ArrayList list = new ArrayList(); // Warning: raw type /* Right way: */ import java.util.ArrayList; ArrayList<Integer> numbers = new ArrayList<>();
Quick Reference
| Action | Syntax Example |
|---|---|
| Create ArrayList | ArrayList |
| Add element | list.add("Hello"); |
| Get element | String item = list.get(0); |
| Remove element | list.remove(0); |
| Check size | int size = list.size(); |
Key Takeaways
Always import java.util.ArrayList before using ArrayList.
Use angle brackets <> to specify the type of elements stored.
Use wrapper classes like Integer for primitive types in ArrayList.
Avoid raw types to prevent warnings and ensure type safety.
Use methods like add(), get(), remove(), and size() to work with ArrayLists.