ArrayLists - Part I
Introduction
The other thing we learned in previous units was arrays in Java. These arrays are fixed, meaning they cannot be added to and removed from after defining them.
This can also be achieved through the ArrayLists. The sizes here are dynamic, i.e. changing the size of the ArrayList is possible.
At this point, we will learn about ArrayLists and also do some basic functions on them.
1. ArrayList
The ArrayList class from the package java.util brings the implementation of resizable arrays feature.
The resizing of sizes occurs automatically for the ArrayLists when adding or removing one or more elements from it. Hence, it is called as a Dynamic Array.
An ArrayList can only hold objects like String. One cannot directly store primitive types.
At the end of this unit, we will see more about storing primitive data types and learn about it.
Syntax
ArrayList<Type> arrList = new ArrayList<>();
Here,
ArrayList is the name of the class.
arrList is the variable name.
Type is the data type of arrList.
Let us create an ArrayList named players of type String.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
}
}
2. Adding Elements to ArrayList
The add() method is used to add a single element to the ArrayList.
Syntax
arrList.add(index, element);
The meaning of 'here' is that
arrList: an object of ArrayList class.
index (optional): at which the element is to be inserted.
element: the element to be inserted.
The add() method works in the same manner that the insert method worked in Python.
If an index is not passed, the element gets added to the end of the ArrayList.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add(0, "Bryant");
players.add("Wade"); // adding element without providing index
}
}
3. Accessing ArrayList Elements
In Arrays, a user is supposed to be able to access elements directly and use brackets in the brackets [] form to write the same. For ArrayLists, however, there are different methods that access and modify the list.
The get() method is used to access a specified element from an ArrayList.
Syntax
arrList.get(index)
The term `index` here specifies the position in the ArrayList from which we need to get the element.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add(0, "Bryant");
players.add("Wade");
System.out.println(players.get(1));
}
}
Output:
Wade
Here we've put the get() method along with the argument as 1. Hence, it returned to us what's at index 1.
4. Printing an ArrayList
The ArrayList can be printed straight forward, while printing an array requires conversion into a String representation.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add(0, "Bryant");
players.add("Wade");
System.out.println(players); // Printing the ArrayList.
}
}
Output:
[Bryant, Wade]
Comparison with Array
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String[] players = {"Bryant", "Wade"};
System.out.println(Arrays.toString(players)); // conversion of array to string for printing
}
}
Output:
[Bryant, Wade]
5. Modifying an ArrayList
To modify or replace an element in an ArrayList, the usual mechanism is to use the set() method.
Syntax
arrList.set(index, element);
Here, the index indicates the position in the ArrayList where the given element is meant to replace an existing element.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add(0, "Bryant");
players.add("Wade");
System.out.println("Before Modification: " + players);
players.set(1, "Garnett"); // Modifying Element at index 1
System.out.println("After Modification: " + players);
}
}
Output:
Before Modification: [Bryant, Wade]
After Modification: [Bryant, Garnett]
The scope of the set() method has been discussed above, with an argument of 1 for replacement of an element at index 1.
Comparison with an Array
Code:
import java.util.*;
class Main {
public static void main(String[] args) {
String[] players = {"Bryant", "Wade"};
System.out.println("Before Modification: " + Arrays.toString(players));
players[1] = "Garnett";
System.out.println("After Modification: " + Arrays.toString(players));
}
}
Output:
Before Modification: [Bryant, Wade]
After Modification: [Bryant, Garnett]
6. Adding Primitive Data Types to ArrayLists
ArrayList holds only objects. The primitive data types have to be converted into their respective object types for manipulation in ArrayLists.
In Java, an equivalent Wrapper Class can be used to convert primitive types into corresponding objects (int, char, float, etc.).
Below are the Wrapper Classes for the corresponding primitive types.
Primitive Type Wrapper Class
byte Byte
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
short Short
An example of the conversion will be:
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> points = new ArrayList<>();
points.add(56);
points.add(75);
points.add(84);
System.out.println(points);
}
}
Output:
[56, 75, 84]
The Integer wrapper class was used in specifying the type while creating an ArrayList here.
7. Autoboxing And UnBoxing
Autoboxing and Unboxing refer to the automatic conversion of primitive types to their corresponding wrapper class objects and vice versa performed by the Java compiler.
Autoboxing
The conversion of primitive types into the corresponding wrapper class objects is called Autoboxing.
Example: int --> Integer, double --> Double, etc
Code
class Main {
public static void main(String[] args) {
int num = 23;
Integer numObj = num; // autoboxing
System.out.println(numObj);
}
}
Output:
23
In the aforementioned code, at the statement Integer numObj = num the conversion of the number 23 from int to Integer object is done automatically by the Java compiler, which is then assigned to numObj.
Unboxing
This is when wrapper classes convert into their corresponding primitive types.
Example: Integer --> int, Double --> double, etc
Code
class Main {
public static void main(String[] args) {
Integer numObj = 23;
int num = numObj; // unboxing
System.out.println(num);
}
}
Output:
23
In the above code, in the statement int num = numObj, the conversion of the number 23 from Integer object to int is done automatically by the Java compiler and is assigned to num.
8. Removing elements from an ArrayList
The remove() method was similar to the pop() method in Python.
It can take either an object or an int value as an argument.
Removing Elements using Index
When an int is passed to the method as an argument, the remove() method removes the object in that index from ArrayList.
Syntax
arrList.remove(index);
Where index is an integer value.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add("Bryant");
players.add("Wade");
players.add("Garnett");
players.add("Rose");
System.out.println("Before Removing: " + players);
players.remove(1); // removing the element at index 1
System.out.println("After Removing: " + players);
}
}
Output:
Before Removing: [Bryant, Wade, Garnett, Rose]
After Removing: [Bryant, Garnett, Rose]
In the above code, index 1 is passed to the remove() method. This removes the element of index 1, i.e., Wade from the ArrayList.
Removing Elements using an Element
when an object is passed as an argument, the remove() method removes the occurrence of the specified element closest to the front from the ArrayList. If it does not find the specified element in the ArrayList, it does not modify the list.
Syntax
arrayList.remove(obj);
Here, obj is an object. For example, String values or the wrapper class objects of primitives.
Example 1:
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add("Bryant");
players.add("Wade");
players.add("Garnett");
players.add("Rose");
System.out.println("Before Removing: " + players);
players.remove("Garnett"); // removing the first occurrence of the element "Garnett"
System.out.println("After Removing: " + players);
}
}
Output:
Before Removing: [Bryant, Wade, Garnett, Rose]
After Removing: [Bryant, Wade, Rose]
Here, in the above code, the element Garnett is passed to the method remove(). Therefore, it removes element Garnett from the ArrayList.
Here is the code:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(8); // autoboxing
numbers.add(3); // autoboxing
numbers.add(5); // autoboxing
numbers.add(1); // autoboxing
System.out.println("Before Removing: " + numbers);
numbers.remove((Integer)5); // removing the first occurrence of the element 5
System.out.println("After Removing: " + numbers);
}
}
Output:
Before Removing: [8, 3, 5, 1]
After Removing: [8, 3, 1]
In the above code, we have used the Integer as a wrapper class so as to convert the primitive int value of 5 into its respective object. Autoboxing does not take place here since method remove() accepts index (int type) as argument and element at specified index has to be removed.
clear()
Similar to that of Python's clear() function, the clear() method removes all elements from the ArrayList.
Syntax
arrList.clear();
Code:
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add("Bryant");
players.add("Wade");
players.add("Garnett");
players.add("Rose");
System.out.println(players) ;
players.clear(); // removing all the elements from the Arraylist
System.out.println(players) ;
}
}
Output:
[Bryant, Wade, Garnett, Rose]
[]
9. Method to get the size of an ArrayList
The method size() is used to determine the size of an ArrayList.
Syntax
arrList.size();
Code:
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> points = new ArrayList<>();
points.add(56); //autoboxing
points.add(75); //autoboxing
points.add(84); //autoboxing
System.out.println(points);
System.out.println(points.size());
}
}
Output:
[56, 75, 84]
3
10. Iterating over an ArrayList
The iteration method based on an array is also applicable to an ArrayList.
In this example, we show iteration through an ArrayList using for-each.
Code
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> players = new ArrayList<>();
players.add(0, "Bryant");
players.add("Wade");
players.add("Garnett");
players.add("Rose");
for (String name : players) {
System.out.println(name);
}
}
}
Output:
Bryant
Wade
Garnett
Rose
Operation in Contrast with Arrays
Code:
class Main {
public static void main(String[] args) {
String[] players = {"Bryant", "Wade", "Garnett", "Rose"};
for(String name: players) {
System.out.println(name);
}
}
}
Output:
Bryant
Wade
Garnett
Rose
Summary
The size of an ArrayList is dynamic, that is, the size of an ArrayList can change.
ArrayLists can store only objects in Java and to store primitive data types, you need to define objects for them.
Wrapper classes can be defined to wrap primitive data types into objects. Autoboxing is the term used for the conversion of primitive types into their corresponding wrapper class objects. Unboxing is the term used for the conversion of wrapper class objects into their corresponding primitive types.
Methods of ArrayList:
`add()`- used to add a single element to an ArrayList.
`get()` - used to fetch an element from an ArrayList.
`set()`- used to modify an element of an ArrayList.
`remove(index)`- Used to remove the element at a specified position, i.e., index, from the ArrayList.
`remove(object)`- Removes the first occurrence of the specified element from the ArrayList, if it is present. Otherwise, the ArrayList remains unchanged.
`size()` - to obtain the size of an ArrayList.
Your code can use a for-each loop to iterate ArrayLists.