CPE207 Object Oriented Programming (Week 11)
CPE207 Object Oriented Programming (Week 11)
Java Collections
An interface is a contract an
implementing class needs to
respect
interface contains behaviors that a
class implements. (Contract)
Methods in an interface are by-
default public. (Contract)
2
Week 12
organisms
3
Week 12
Multiple inheritance is not
allowed in Java. But classes
can inherit multiple
interfaces.
4
5
The Collection in Java is a framework
that provides an architecture to store
and manipulate the group of objects.
◦ data structures and methods
written by pioneers in the
field
Joshua Bloch, who wrote the Java
Collections Framework, the
java.math package and many
more...
Joshua Bloch 6
Java Collections can achieve all the operations that you
perform on a data such as searching, sorting, insertion,
manipulation, and deletion.
A collections framework contains three things:
◦ Interfaces.
(Set, List, Queue, Deque)
◦ Implementations (classes),
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet,LinkedHashSet,
TreeSet)
◦ Algorithms
7
The java.util package
contains all the classes
and interfaces for the
Collection framework.
Source: https://www.javatpoint.com/collections-in-java 8
There are many methods declared in the Collection interface such as:
int size(); //It returns the total number of elements in the collection.
boolean isEmpty();
boolean contains(Object element); //It is used to search an element.
boolean add(Object element); //to insert an element in this collection.
boolean remove(Object element); // to delete an element from the collection.
Iterator iterator(); // what is this?
These methods are enough to define the basic behavior of a
collection
This Interface provides an Iterator to step through the
elements in the Collection
9
Defines three Iterator enables you to cycle through a
collection, obtaining or removing elements.
fundamental methods
These three methods provide access to the
Object next() contents of the collection
It returns the element and
An Iterator knows position within collection
moves the cursor pointer to
the next element.
Each call to next() “reads” an element from the
collection. Then you can use it or remove it
boolean hasNext()
void remove()
10
When next() is called
while(iterator.hasNext()){
System.out.println(iterator.next());
iterator.remove();
}
list element1 element2 element3 element4
hasNext ==false
hasNext ==true
11
If you only want to scan through the list, then this is enough:
12
You can put any types of data. But!
Don’t do this.
13
“Don’t use raw types” Joshua Bloch- Effective Java Third Edition. Ch. 5 Page 117
Let's say you want to put a single data type and If someone
accidentally inserted an object of the wrong type, casts could fail at
runtime.
With generics, you tell the compiler what types of objects are
permitted in each collection (type-safety)
We are not going to use : List elements = new …
Rather we use, List<YourObjectType> elements = new …
This will be called as generics later.
14
15
List interface is the child interface of Collection interface.
List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
The List interface adds the concept of order to a
collection
The user of a list has control over where an element is
added in the collection
Lists typically allow duplicate elements
Provides a ListIterator to step through the elements in the
list.
16
To instantiate the List interface, we must use :
◦ List <data-type> list1= new ArrayList();
◦ List <data-type> list2 = new LinkedList();
◦ List <data-type> list3 = new Vector();
◦ List <data-type> list4 = new Stack();
There are various methods in List interface that
can be used to insert, delete, and access the
elements from the list.
17
18
Extends the Iterator interface
Defines three fundamental methods
void add(Object o)
boolean hasPrevious()
Object previous()
The addition of these three methods defines the basic
behavior of an ordered list
A ListIterator knows position within list
19
returning element : iterator.previous()
hasPrevious ==false
hasNext ==false
hasPrevious ==true
iterator
hasNext ==true
When hasPrevious() is called
20
public class ListIteratorExample {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
linkedlist.add(“Abant"); // Add elements to LinkedList
linkedlist.add(“Mengen");
linkedlist.add(“Gerede");
ListIterator listIt = linkedlist.listIterator(); // Obtaining ListIterator
System.out.println("Forward iteration:");
// Iterating the list in forward direction
while(listIt.hasNext())
System.out.println(listIt.next());
// Iterating the list in backward direction
System.out.println("\nBackward iteration:");
while(listIt.hasPrevious())
System.out.println(listIt.previous());
}
}
21
22
ArrayList LinkedList
◦ low cost random access sequential access
◦ high cost insert and delete
low cost insert and delete
high cost random access
23
Constant time (O(1)) positional access (it’s an array)
The indexed get and set methods of the List interface are appropriate to
use since ArrayLists are backed by an array
Object get(int index)
Object set(int index, Object element)
Indexed add and remove are provided, but can be costly if used frequently
void add(int index, Object element)
Object remove(int index)
May want to resize in one shot if adding many elements
void ensureCapacity(int minCapacity)
As elements are added to an ArrayList, its capacity grows automatically.
24
set get
25
add remove
26
Stores each element in a node
Each node stores a link to the next and previous nodes
Insertion and removal are low-cost
just update the links in the surrounding nodes
Random access is expensive
Start from beginning or end and traverse each node while
counting
27
The list is sequential, so access it that way
◦ ListIterator listIterator()
ListIterator knows about position
◦ use add() from ListIterator to add at a position
◦ use remove() from ListIterator to remove at a position
LinkedList knows a few things too
◦ void addFirst(Object o), void addLast(Object o)
◦ Object getFirst(), Object getLast()
◦ Object removeFirst(), Object removeLast()
28
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
//create LinkedList
Collection <String> list2 = new LinkedList<>();
// add elements to LinkedList
list2.add(“jade");
list2.add(“June");
list2.add(“April");
}
}
29
Lab exercise
Write a class called BankAccount. The class must have 3 attributes: accountNo(int),
holderName(String) and balance(double).
a) Class constructor will have to set these 3 attributes.
b) Create a balanceChange(double amount) method to reduce balance value by given
amount.
c) In the Main method:
1. Create 4 objects (a1, a2, a3, a4) from this class and add them all to an
ArrayList called myAccounts. List will only accept BankAccount type.
2. Sort objects by holderName in the list. (Hint: implement Comparable
interface)
3. Reduce the balances by 500 for all the accounts and print sorted objects in the
list.
30
31