Lecture4 - ArrayList
Lecture4 - ArrayList
1 1
LECTURE 4 OBJECTIVES
Understand the benefits of using the ArrayList
class and some of its common methods.
2 2
ARRAYS CAN BE USED AS FIELDS WITHIN CLASSES TO
MAKE OTHER DATA STRUCTURES
Stack<T>
A stack of some
- stackArray : T[] type, T
The data
store
- top : int
Index of last
+ push(T) element
+ pop()
Typical stack
methods + top() : T
+ isEmpty() : boolean
3
THE ARRAYLIST CLASS
An array's size is fixed upon creation – we do not always
know how many items we wish to store in a collection.
4
JAVA.UTIL.ARRAYLIST<T>
The Java SDK provides a class ArrayList, placed within the
java.util package that:
encapsulates an array of objects.
5
EXAMPLE OF A SIMPLE GENERIC CLASS
public class Pair<T, S> {
private T first;
private S second;
public Pair(T f, S s) {
first = f; second = s;
}
public T getFirst() {
return first;
} //…etc
6
USING THE GENERIC CLASS
//using class with different types…
Pair<String, Integer> fruit = new
Pair<String, Integer>("Apple", 1);
String x = fruit.getFirst();
7
INSTANTIATING AN ARRAYLIST
Examples of instantiating an ArrayList with different type
parameters:
ArrayList<String> words = new ArrayList<String>();
8
JAVA 7 DIAMOND SYNTAX
Java 7 has introduced a convenient syntax enhancement
for declaring array lists and other generic classes.
9
WRAPPERS AND AUTO-BOXING
Java has a wrapper class for each of the primitive types,
e.g. Integer for int, Double for double, etc.
11
ARRAYLIST: SIZE V CAPACITY
When an ArrayList is first created it receives an initial
capacity of 10 elements.
12
USING THE LIST INTERFACE TYPE
An ArrayList object can be stored in a variable container of
type List – this is a common interface for all list types in the
Java collections framework:
List<String> list = new ArrayList<>();
ArrayList<String> list = new ArrayList<>();
13
LIST INTERFACE’S IMPLEMENTING CLASSES
View the API at:
https://docs.oracle.com/javase/8/docs/api/java/util/List.html
14
ARRAYLIST: A COLLECTION OF REFERENCES
When we instantiate an ArrayList of different types, how
much memory is allocated? e.g.
List<String> s = new ArrayList<>();
15
USING A FOR-EACH LOOP
Like a for-i loop but has a simplified syntax. It can be used
with an array or a collection class (e.g. ArrayList).
Syntax is:
18
ARRAYLIST OF OBJECTS: EXAMPLE (2)
Using a for-each loop you cannot update the object
reference stored in an ArrayList, but you can modify the
internal data of an object, e.g. Setting quantity:
19
THE JAVA 8 FOREACH METHOD
The addition of functional programming constructs in the
8th release of Java has provided another way of
processing collections – the forEach method.
For one line method bodies, you can omit both the braces {} and
the return keyword. Parameter types can often be inferred from
the context of the surrounding code.
orderList.forEach((Order od) -> { od.getCost(); });
21
STREAMS CAN OPERATE ON COLLECTIONS
A stream represents a sequence of elements on which one
or more operations can be performed.
22
EXAMPLES USING STREAMS
int total = orderlist.stream().mapToInt((Order od)
-> { return od.getCost(); }).sum();
int total = orderlist.stream().mapToInt( od ->
od.getCost()).sum(); //with valid omissions
----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------
register.stream().filter(n ->
n.getFirstName().length() < 5).map(n ->
n.getFamilyName()).forEach(f ->
System.out.println(f)); //what will print out?
23
HOW DO I CHOOSE THE FORMAT OF A
LAMBDA EXPRESSION?
A lambda expression can be substituted wherever a
functional interface is expected:
⚫A functional interface contains only a single abstract method.
⚫The lambda expression should match the parameter-list and return
type of the abstract method.
26
CHOOSING AN ARRAYLIST OR ARRAY?
Use an array if:
the size of the collection never changes.
you collect a long sequence of primitive type values and you are
concerned about efficiency (auto-boxing takes time).
27
OVERRIDING EQUALS – COMMON MISTAKE
A common mistake is to set the parameter type to be
the same as the class type, instead of Object, e.g.
@Override
public boolean equals(Object obj) {
28 28
NOTE: OVERLOADING METHODS
An overloaded method is simply a method with the same
name that is declared more than once with a different
parameter-list.
29 29
SO WHAT IS THE ISSUE?
If we accidently overload equals(Object) with our
own version then what is actually the issue?
30 30
ARRAYLIST CONTAINS(...) METHOD
When you have an ArrayList instance populated with
objects of a given type, you can test if the list already
contains an object.
31 31
ARRAYLIST REMOVE(OBJECT) METHOD
The equals method is used by other ArrayList methods
such as remove, which removes the provided object.
For example
//add lots of name objects
Name n = new Name("Joe", "Bloggs");
if ( names.remove(n) )
//name found and successfully removed
else
//name not found
32 32
SUGGESTED READING
Big Java : Early Objects (5th Ed.) Cay, S. Horstmann
⚫Chapter 6: Arrays and Array Lists
⚫Section 2.9.2: The null Reference
35 35
EXERCISE 4.2
4.2 Copy the Order that you have created the Lab to your current Java project and then
create a new class called “OrderListTest“.
Create an ArrayList of type Name (i.e. List<Order> orderList = new
ArrayList<>();).
a. Add five different orders to the orderList.
b. Use the forEach method to output the id and cost of each order. You should use lambda
expression.
c. Using stream().mapToInt(… ).sum(); create a stream pipeline to output the total
cost of the orders in the orderList.
.
Submission:
Upload your java files
NameListTest.java and OrderListTest.java to the google drive folder that your
have shared with the email ([email protected]) by 10:00 am, 7th July, 2021.
36 36