You are on page 1of 31

1

ARRAYLISTS
2

What’s an Array List


• ArrayList is
• a class in the standard Java libraries that can hold any type of
object
• an object that can grow and shrink while your program is running
(unlike arrays, which have a fixed length once they have been
created)
• elements can be added and removed from an ArrayList whenever
you want.
• In general, an ArrayList serves the same purpose as an array,
except that an ArrayList can change length while the program is
running
3

Using the ArrayList Class


• In order to make use of the ArrayList class, it must
first be imported
import java.util.ArrayList;
• An ArrayList is created and named in the same
way as object of any class, except that you specify
the base type as follows:
ArrayList<BaseType> aList =
new ArrayList<BaseType>()
Note that the base type of an ArrayList is specified as a
type parameter
4

List ADT
• A list is a dynamic ordered tuple of homogeneous
elements
Ao, A1, A2, …, AN-1
where Ai is the i-th element of the list
• The position of element Ai is i; positions range from 0 to
N-1 inclusive
• The size of a list is N ( a list with no elements is called an
“empty list”)
5

Generic Operations on a List


• create an empty list
• printList() – prints all elements in the list
• construct a (deep) copy of a list
• find(x) – returns the position of the first
occurrence of x
• remove(x) – removes x from the list if
present
• insert(x, position) – inserts x into the list at
the specified position
• isEmpty( ) – returns true if the list has no
elements
• makeEmpty( ) – removes all elements from
the list
• findKth(int k) – returns the element in the
specified position
6

ArrayList features
• think of it as an auto-resizing array that can hold any type
of object, with many convenient methods

• maintains most of the benefits of arrays, such as fast


random access

• frees us from some tedious operations on arrays, such as


sliding elements and resizing

• can call toString on an ArrayList to print its elements


• [1, 2.65, Marty Stepp, Hello]
7

Generic classes
• generic class: A type in Java that is written to accept
another type as part of itself.
• Generic ("parameterized") type has one or more other types'
names written between < and > .

• ArrayList<E> is a generic class.


• The <E> is a placeholder in which you write the type of elements you
want to store in the ArrayList.

• Example:
ArrayList<String> words = new ArrayList<String>();
• Now the methods of words will manipulate and return Strings.
ArrayList methods (10.1)
add(value) appends value at end of list
add(index, value) inserts given value just before the given index,
shifting subsequent values to the right
clear() removes all elements of the list
indexOf(value) returns first index where given value is found
in list (-1 if not found)
get(index) returns the value at given index
remove(index) removes/returns value at given index, shifting
subsequent values to the left
set(index, value) replaces value at given index with given value
size() returns the number of elements in list
toString() returns a string representation of the list
such as "[3, 42, -7, 15]"
ArrayList methods 2
addAll(list) adds all elements from the given list to this list
addAll(index, (at the end of the list, or inserts them at the given index)
list)
contains(value) returns true if given value is found somewhere in this list
containsAll(list) returns true if this list contains every element from given list
equals(list) returns true if given other list contains the same elements
iterator() returns an object used to examine the contents of the list
listIterator() (seen later)
lastIndexOf(value returns last index value is found in list (-1 if not found)
)
remove(value) finds and removes the given value from this list
removeAll(list) removes any elements found in the given list from this list
retainAll(list) removes any elements not found in given list from this list
subList(from, to) returns the sub-portion of the list between
indexes from (inclusive) and to (exclusive)
10

ArrayList vs. array


• array
String[] names = new String[5];
names[0] = "Jennifer";
String name = names[0];

• ArrayList
ArrayList<String> namesList = new
ArrayList<String>();
namesList.add("Jennifer");
String name = namesList.get(0);
ArrayList vs. array
• doing something to each value that starts with "B"
for (int i = 0; i < names.length; i++) {
if (names[i].startsWith("B")) { ... }
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).startsWith("B")) { ... }
}

• seeing whether the value "Benson" is found


for (int i = 0; i < names.length; i++) {
if (names[i].equals("Benson")) { ... }
}
if (list.contains("Benson")) { ... }
12

Adding elements
• Elements are added dynamically to the list:
ArrayList<String> list = new ArrayList<String>();
System.out.println("list = " + list);
list.add(“UAE");
System.out.println("list = " + list);
list.add(“India");
System.out.println("list = " + list);
list.add(“UK");
System.out.println("list = " + list);

• Output:
list = []
list = [UAE]
list = [UAE, India]
list = [UAE, India, UK]
13

ArrayList vs. array


• array
String[] names = new String[5];
names[0] = "Jennifer";
String name = names[0];

• ArrayList
ArrayList<String> namesList = new
ArrayList<String>();
namesList.add("Jennifer");
String name = namesList.get(0);
• Elements can also be removed by index:
System.out.println("before remove list = " +
list);
list.remove(0);
list.remove(1);
System.out.println("after remove list = " + list);
15

Removing elements
• Output:
• before remove list = [UAE, India, UK, USA]
after remove list = [India, USA]
• Notice that as each element is removed, the others shift downward
in position to fill the hole.
• Therefore, the second remove gets rid of UK, not India.

index 0 1 2 3
value UAE India UK USA

inde 0 1
x
value India USA
16

Searching for elements


• You can search the list for particular elements:
if (list.contains(“India")) {
int index = list.indexOf(" India ");
System.out.println(index + " " + list.get(index));
}
if (list.contains(" Australia")) {
System.out.println(" Australia is in the list");
} else {
System.out.println(" Australia is not found.");
}

• Output:
1 India
Australia is not found.
• contains tells you whether an element is in the list or not, and
indexOf tells you at which index you can find it.
17

ArrayList and for loop


• enhanced for loop syntax :
for (<type> <name> : <collection>) {
<statement(s)>;
}

• This syntax can be used to examine an ArrayList:


int sum = 0;
for (String s : list) {
sum += s.length();
}
System.out.println("Total of lengths = " + sum);
18

Wrapper classes
• ArrayLists only contain objects, and primitive values are not objects.
• e.g. ArrayList<int> is not legal

• If you want to store primitives in an ArrayList, you must declare it


using a "wrapper" class as its type.
Primitive Wrapper
type class
int Integer
double Double
char Character
boolean Boolean

• A wrapper is an object whose sole purpose is to hold a primitive value.


• example:
ArrayList<Integer> list = new ArrayList<Integer>();
19

Wrapper example
• The following list stores int values:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(13);
list.add(47); inde 0 1 2 1
list.add(15); x
list.add(9);
int sum = 0; value 13 47 15 9
for (int n : list) {
sum += n;
}
System.out.println("list = " + list);
System.out.println("sum = " + sum);

• Output:
list = [13, 47, 15, 9]
sum = 84
20

• Create an ArrayList object called cars that will store


strings:

• import java.util.ArrayList; // import the ArrayList class

• ArrayList<String> cars = new ArrayList<String>(); //


Create an ArrayList Object
21

Add Items to ArrayList


To add elements to the ArrayList, use the add() method:

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
22

https://devcom.w3schools.com/java/tryjava.
asp?filename=demo_compiler
23

Access an Item
To access an element in the ArrayList, use the get() method and refer to the index
number

To access an element in the ArrayList, use the get() method and refer to the index
number:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars.get(0));
}
}
24

https://devcom.w3schools.com/java/tryjava.
asp?filename=demo_compiler
25

Change an Item
To modify an element, use the set() method and refer to the index
number:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.set(0, "Opel");
System.out.println(cars);
}
}
26

https://devcom.w3schools.com/java/tryjava
.asp?filename=demo_compiler
27

Remove an Item
To remove an element, use the remove() method and refer to the index
number:

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.remove(0);
System.out.println(cars);
}
}
28

https://devcom.w3schools.com/java/tryjava
.asp?filename=demo_compiler
29

To remove all the elements in the ArrayList, use the clear() method:

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.clear();
System.out.println(cars);
}
}
30

ArrayList Size
To find out how many elements an ArrayList have, use the size method:
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars.size());
}
}
31

https://devcom.w3schools.com/java/tryjava
.asp?filename=demo_compiler

You might also like