ArrayLists in Java
Limitations of Arrays
Arrays have a fixed size, which can be a limitation when the required size is unknown or changes during program execution.
Arrays provide only low-level access using
getandsetmethods.
Introduction to ArrayLists
ArrayLists are dynamic arrays that automatically resize as needed.
They offer additional helpful methods beyond basic
getandset.
Creating ArrayLists
Import the ArrayList class from the
java.utilpackage:import java.util.*;(imports all classes in the package)import java.util.ArrayList;(imports only the ArrayList class)
Declare an empty ArrayList of a specific type using angle brackets:
ArrayList<String> list = new ArrayList<String>();(creates an ArrayList to store strings)The type within the angle brackets specifies the type of elements the ArrayList will hold.
Templatized Types
ArrayLists require specifying the type they will store using angle brackets (e.g.,
<String>,<Integer>).To store primitive types, use the corresponding wrapper classes:
IntegerforintDoublefordouble
Auto-boxing and Unboxing
Java automatically handles the conversion between primitive types and their corresponding wrapper objects.
Auto-boxing: Converting a primitive type to its wrapper object (e.g.,
inttoInteger).Unboxing: Converting a wrapper object to its primitive type (e.g.,
Integertoint).
Adding Elements to an ArrayList
Use the
addmethod to append elements to the end of the list:list.add(5);list.add(3);list.add(10);list.add(4);
Getting Values from an ArrayList
Use the
getmethod to retrieve a value at a specific index:int val = list.get(1);(retrieves the value at index 1, which is 3 in this case)
Setting Values in an ArrayList
Use the
setmethod to change a value at a specific index:list.set(2, 88);(sets the value at index 2 to 88)
Getting the Size of an ArrayList
Use the
sizemethod to determine the number of elements in the ArrayList:list.size()(returns the number of elements in the list)Important Difference:
size()returns the number of elements in the list, while for arrays,lengthis a property denoting the fixed size of an array.
Looping Over an ArrayList
Standard
forloop:java for (int i = 0; i < list.size(); i++) { int element = list.get(i); // Use element }
Enhanced
forloop (for-each loop):java for (int elm : list) { // Use elm }The enhanced
forloop iterates through each element in the list, assigning the element to the variableelm.
Quick Reference of ArrayList Methods
size(): Returns the number of elements in the list (anint).add(E elem): Adds the elementelemto the end of the list.Erepresents the templatized type of the ArrayList.E get(int index): Returns the element at the specifiedindex.Erepresents the templatized type of the ArrayList.remove(int index): Removes the element at the specifiedindexand shifts subsequent elements.add(int index, E element): Inserts theelementat the specifiedindexand shifts subsequent elements.
ArrayList and the List Interface
The ArrayList class implements the List interface.
This allows for using the List interface type on the left-hand side of a declaration:
List<String> myList = new ArrayList<String>();
Other classes can also implement the List interface, but the focus here is on ArrayList.
ArrayList Examples
Creating an ArrayList of Strings:
ArrayList<String> myList = new ArrayList<String>();myList.add("Hello");myList.add("World");Printing elements:
System.out.println(myList.get(0));(prints "Hello")System.out.println(myList.get(1));(prints "World")
Using ArrayList with primitive types (Integer):
ArrayList<Integer> myList = new ArrayList<Integer>();myList.add(100);myList.add(200);Java handles the auto-boxing of
inttoInteger.
Using the
sizemethod:java ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { numbers.add(i); } System.out.println(numbers.size()); // Prints 100
Simulating a reading list (ArrayList of Strings):
Demonstrates various
addandremovemethods.Also shows
indexOfusage.
ArrayList as an Instance Variable
Example: Simulating a cell phone with a list of text messages.
It contains the classes:
TextMessageandCellPhoneTextMessageClass:Attributes: message (String), sender (String), receiver (String).
\begin{array}{ll} \text{message} & \text{The content of the text message} \\ \text{sender} & \text{The sender of the text message} \\ \text{receiver} & \text{The receiver of the text message} \end{array}Constructor to initialize these attributes.
toStringmethod to represent the message.
CellPhoneClass:Attribute:
ArrayList<TextMessage> textsto store text messages.Constructor initializes the
ArrayList.addText(TextMessage text)method adds a text message to the list.getTextMessages()method returns the list of text messages.