Unit 7: ArrayLists
Creating ArrayLists in Java
Introduction to ArrayLists
In Java, arrays are useful, but they have a fixed length. This limitation can often be restrictive. The ArrayList class, part of Java's java.util package, is a resizable array, which can be found in the Java Collections Framework (JCF). They provide more flexibility and functionality compared to arrays.
Fundamentals of ArrayLists
Why use ArrayLists?
ArrayLists are dynamic. This means you can:
- Add items
- Remove items
- Get items
- Set items
All without needing to manage the size of the collection!
Declaring and Initializing ArrayLists
To use the ArrayList class, it needs to be imported:
import java.util.ArrayList;
Creating an ArrayList:
ArrayList<String> fruits = new ArrayList<>();
Here, String denotes the type of elements the ArrayList will hold. You can replace String with other types like Integer, Double, etc., to store different types of elements.
Methods in ArrayList
Adding elements
To add an element to the ArrayList:
fruits.add("Apple");
fruits.add("Banana");
Accessing elements
To access an element:
String fruit = fruits.get(0); // This will retrieve "Apple"
Removing elements
To remove an element:
fruits.remove(0); // This will remove "Apple"
Other Useful Methods
ArrayList class comes with a plethora of useful methods. Some of them are:
- size(): returns the number of elements
- clear(): removes all the elements from the ArrayList
- isEmpty(): checks if the list is empty
Using Generics
Notice the use of < > with ArrayList. This is Java's generics feature. It allows you to ensure that the ArrayList contains a certain type of object. It adds a layer of type safety.
Summary
ArrayList in Java provides a dynamic and flexible way to store elements. They can grow and shrink automatically and provide a rich set of methods to manipulate data. Compared to arrays, ArrayLists offer more powerful, flexible, and convenient options for storing and manipulating data. However, understanding when to use ArrayList versus traditional arrays is key for effective programming.
References
AP CSA Homework Assignment
Assignment: Exploring ArrayLists in Java
Instructions
- Create a Java class named ArrayListExplorer.
- Demonstrate the creation of an ArrayList of type Double.
- Add, remove, and access elements in the ArrayList.
- Use at least 5 different methods from the ArrayList class.
- Reflect on scenarios where you'd prefer to use an ArrayList over a traditional array.