0% found this document useful (0 votes)
40 views

Java Collections Framework: Licensing Note

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Java Collections Framework: Licensing Note

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Java Collections Framework

Object-Oriented Programming

https://softeng.polito.it/courses/09CBI
Version 4.1.0 - April 2020
© Maurizio Morisio, Marco Torchiano, 2020

Licensing Note
This work is licensed under the Creative Commons Attribution-
NonCommercial-NoDerivatives 4.0 International License.
To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-nd/4.0/.
You are free: to copy, distribute, display, and perform the work

Under the following conditions:


§ Attribution. You must attribute the work in the manner specified by
the author or licensor.

§ Non-commercial. You may not use this work for commercial


purposes.

§ No Derivative Works. You may not alter, transform, or build upon


this work.

§ For any reuse or distribution, you must make clear to others the
license terms of this work.
§ Any of these conditions can be waived if you get permission from the
copyright holder.

Your fair use and other rights are in no way affected by the above. 2
Collections Framework
§ Interfaces (ADT, Abstract Data Types)
§ Implementations (of ADT)
§ Algorithms (sort)
§ Contained in the package java.util

§ Originally using Object, since Java 5


redefined as generic

Interfaces
Iterable<E>

Collection<E> Map<K,V>

Set<E> Queue<E> List<E>

SortedMap<K,V>
SortedSet<E>

Associative containers
Group containers

4
Implementations
Collection<E> Interfaces Map<K,V>

Set<E> Queue<E> List<E> Sorted


Map<K,V>

Sorted
Set<E>

HashSet Linked Array HashMap TreeMap


List List
Linked
HashSet Linked
Priority HashMap
Queue
TreeSet Classes
5

Internals
interface
data structure

Set List Map

Hash table HashSet HashMap

Balanced tree TreeSet TreeMap

Resizable array ArrayList

Linked list LinkedList

HT + LL LinkedHashSet LinkedHashMap

classes
6
Collection<E>

Set<E> Queue<E> List<E>

SortedSet<E>

GROUP CONTAINERS (COLLECTIONS)

Collection
§ Group of elements (references to objects)
§ It is not specified whether they are
w Ordered / not ordered
w Duplicated / not duplicated
§ Implements Iterable
§ All classes implementing Collection shall
provide two constructors
w C()
w C(Collection c)

8
Collection interface
int size()
boolean isEmpty()
boolean contains(E element)
boolean containsAll(Collection<?> c)
boolean add(E element)
boolean addAll(Collection<? extends E> c)
boolean remove(E element)
boolean removeAll(Collection<?> c)
void clear()
Object[] toArray()
Iterator<E> iterator()

Collection example
Collection<Person> persons =
new LinkedList<Person>();
persons.add( new Person(“Alice”) );
System.out.println( persons.size() );
Collection<Person> copy =
new TreeSet<Person>();
copy.addAll(persons);//new TreeSet(persons)
Person[] array = copy.toArray();
System.out.println( array[0] );

10
List
§ Can contain duplicate elements
§ Insertion order is preserved
§ User can define insertion point
§ Elements can be accessed by position
§ Augments Collection interface

11

List interface
E get(int index)
E set(int index, E element)
void add(int index, E element)
E remove(int index)

boolean addAll(int index,Collection<E> c)


int indexOf(E o)
int lastIndexOf(E o)
List<E> subList(int from, int to)

12
List implementations
§ ArrayList<E>
w ArrayList()
w ArrayList(int initialCapacity)
w ArrayList(Collection<E> c)
w void ensureCapacity(int minCapacity)

§ LinkedList<E>
w void addFirst(E o)
w void addLast(E o)
w E getFirst()
w E getLast()
w E removeFirst()
w E removeLast()

13

Example
List<Integer> l = new ArrayList<>();

l.add(42); // 42 in position 0
l.add(0, 13); // 42 moved to position 1
l.set(0, 20); // 13 replaced by 20
int a = l.get(1); // returns 42
l.add(9, 30); // NO: out of bounds

IndexOutOfBoundsException

14
Example II

Car[] garage = new Car[20];

garage[0] = new Car();


garage[1] = new ElectricCar();
garage[2] = new ElectricCar();
garage[3] = new
List<Car>
Car(); garage = new ArrayList<Car>(20);

for(int i=0; garage.set(


i<garage.length;
0, newi++){
Car() );
garage.set( 1, new ElectricCar() );
garage[i].turnOn();
} garage.set( 2, new ElectricCar() );
garage.set( 3, new Car());

for(int i; i<garage.size(); i++){


Car c = garage.get(i);
Null pointer error
c.turnOn();
}

15

Example LinkedList
LinkedList<Integer> ll =
new LinkedList<Integer>();

ll.add(new Integer(10));
ll.add(new Integer(11));

ll.addLast(new Integer(13));
ll.addFirst(new Integer(20));

//20, 10, 11, 13

16
Queue interface
§ Collection whose elements are inserted
using an
w Insertion order (FIFO)
w Element order (Priority queue)
§ Defines a head position where is the
first element that can be accessed
w peek()
w poll()

17

Queue implementations
§ LinkedList
w head is the first element of the list
w FIFO: Fist-In-First-Out
§ PriorityQueue
w head is the smallest element

18
Queue example
Queue<Integer> fifo =
new LinkedList<Integer>();
Queue<Integer> pq =
new PriorityQueue<Integer>();
fifo.add(3); pq.add(3);
fifo.add(1); pq.add(1);
fifo.add(2); pq.add(2);
System.out.println(fifo.peek()); // 3
System.out.println(pq.peek()); // 1

19

Set interface
§ Contains no methods
w Only those inherited from Collection
§ add()has the restriction that no
duplicate elements are allowed
w e1.equals(e2) == false " e1,e2 Î S

§ Iterator
w The elements are traversed in no
particular order

20
SortedSet interface
§ No duplicate elements
§ Iterator
w The elements are traversed according to the
natural ordering (ascending)
§ Augments Set interface
w E first()
w E last()
w SortedSet<E> headSet(E toElement)
w SortedSet<E> tailSet(E fromElement)
w SortedSet<E> subSet(E from, E to)

21

Set implementations
§ HashSet implements Set
w Hash tables as internal data structure
(faster)
§ LinkedHashSet extends HashSet
w Elements are traversed by iterator
according to the insertion order

§ TreeSet implements SortedSet


w R-B trees as internal data structure
(computationally expensive)

22
Note on sorted collections
§ Depending on the constructor used
they require different implementation
of the custom ordering
§ TreeSet()
w Natural ordering (elements must be
implementations of Comparable)
§ TreeSet(Comparator c)
w Ordering is according to the comparator
rules, instead of natural ordering

23

Generic collections
§ Since Java 5, all collection interfaces
and classes have been redefined as
Generics
§ Use of generics leads to code that is
w safer
w more compact
w easier to understand
w equally performing

24
Object list - excerpt
public interface List{
void add(Object x);
Object get(int i);
Iterator<E> iterator();
}
public interface Iterator{
Object next();
boolean hasNext();
}

25

Example
§Using a list of Integers
w Without generics ( ArrayList list )
list.add(0, new Integer(42));
int n= ((Integer)(list.get(0))).intValue();
w With generics ( ArrayList<Integer> list )
list.add(0, new Integer(42));
int n= ((Integer)(list.get(0))).intValue();
w + autoboxing ( ArrayList<Integer> list )
list.add(0,new Integer(42));
int n = ((Integer)(list.get(0))).intValue();

26
ITERATORS

Iterable interface
§ Container of elements that can be
iterated upon
§ Provides a single instance method:
Iterator<E> iterator()
w It returns the iterator on the elements of
the collection
§ Collection extends Iterable
Iterators and iteration
§ A common operation with collections
is to iterate over their elements
§ Interface Iterator provides a
transparent means to cycle through all
elements of a Collection
§ Keeps track of last visited element of
the related collection
§ Each time the current element is
queried, it moves on automatically
29

Iterator
§ Allows the iteration on the elements of a
collection
§ Two main methods:
w boolean hasNext()
– Checks if there is a next element to iterate on
w E next()
– Returns the next element and advances by one
position
w void remove()
– Optional method, removes the current element
Iterator examples
Print all objects in a list

Iterable<Person> persons =
new LinkedList<Person>();

for(Iterator<Person> i = persons.iterator();
i.hasNext(); ) {
Person p = i.next();

System.out.println(p);
}

31

Iterator examples
The for-each syntax avoids
using iterator directly

Iterable<Person> persons =
new LinkedList<Person>();

for(Person p: persons) {

System.out.println(p);
}

32
Iterator examples (until Java 1.4)

Print all objects in a list

Collection persons = new LinkedList();



for(Iterator i= persons.iterator(); i.hasNext(); ) {
Person p = (Person)i.next();

}

33

Iterable forEach
§ Iterable defines the default method
forEach(Consumer<? super T> action)
§ Can be used to perform operations of
elements with a functional interface

Iterable<Person> persons;

persons.forEach( p -> {
System.out.println(p);
});
Note well
§ It is unsafe to iterate over a collection
you are modifying (add/remove) at the
same time

§ Unless you are using the iterator’s


own methods
w Iterator.remove()
w ListIterator.add()

35

Delete
List<Integer> lst=new LinkedList<Integer>();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));

int count = 0;
for (Iterator<?> itr = lst.iterator();
itr.hasNext(); ) {
itr.next();
if (count==1)
lst.remove(count); // wrong
count++;
}
ConcurrentModificationException

36
Delete (cont’d)
List<Integer> lst=new LinkedList<Integer>();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (Iterator<?> itr = lst.iterator();
itr.hasNext(); ) {
itr.next();
if (count==1)
itr.remove(); // ok
count++;
} Correct

37

Add
List lst = new LinkedList();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (Iterator itr = lst.iterator();
itr.hasNext(); ) {
itr.next();
if (count==2)
lst.add(count, new Integer(22));//wrong
count++;
}
ConcurrentModificationException

38
Add (cont’d)
List<Integer> lst=new LinkedList<Integer>();
lst.add(new Integer(10));
lst.add(new Integer(11));
lst.add(new Integer(13));
lst.add(new Integer(20));
int count = 0;
for (ListIterator<Integer> itr =
lst.listIterator(); itr.hasNext();){
itr.next();
if (count==2)
itr.add(new Integer(22)); // ok
count++;
}
Correct

39

Map<K,V>

SortedMap<K,V>

ASSOCIATIVE CONTAINERS (MAPS)


Map
§ A container that associates keys to values
(e.g., SSN ⇒ Person)
§ Keys and values must be objects
§ Keys must be unique
w Only one value per key

§ Following constructors are common to all


collection implementers
w M()
w M(Map m)

41

Map interface
§ V put(K key, V value)
§ V get(K key)
§ Object remove(K key)
§ boolean containsKey(K key)
§ boolean containsValue(V value)
§ public Set<K> keySet()
§ public Collection<V> values()
§ int size()
§ boolean isEmpty()
§ void clear()

42
Map example: put and get
Map<String,Person> people =new HashMap<>();
people.put( “ALCSMT”, //ssn
new Person(“Alice”, “Smith”) );
people.put( “RBTGRN”, //ssn
new Person(“Robert”, “Green”) );

if( ! people.containsKey(“RBTGRN”))
System.out.println( “Not found” );

Person bob = people.get(“RBTGRN”);

int populationSize = people.size();

43

Map ex.: values and keySet


Map<String,Person> people =new HashMap<>();
people.put( "ALCSMT", //ssn
new Person("Alice", "Smith") );
people.put("RBTGRN", //ssn
new Person("Robert", "Green") );
// Print all people
for(Person p : people.values()){
System.out.println(p);
}
// Print all ssn
for(String ssn : people.keySet()){
System.out.println(ssn);
}

44
SortedMap interface
§ The elements are traversed according
to the keys’ natural ordering
w Or using comparator passed to ctor
§ Augments Map interface
w SortedMap subMap(K fromKey, K toKey)
w SortedMap headMap(K toKey)
w SortedMap tailMap(K fromKey)
w K firstKey()
w K lastKey()

45

Map implementations
§ Analogous to Set
§ HashMap implements Map
w No order
§ LinkedHashMap extends HashMap
w Insertion order
§ TreeMap implements SortedMap
w Ascending key order

46
OPTIONAL

Nullability problem
§ The typical convention in Java APIs is
to let a method return a null
reference to represent the absence of
a result.
§ The caller must check the return value
of the method
§ When appropriate checks are not
applied, may lead to NPEs
Optional
§ Optional represents a potential value
§ Methods returning Optional<T> make
explicit that return value may be
missing
w Forces the clients to deal with potentially
empty optional

Optional<T>
§ Access to embedded value through
w boolean isPresent()
– checks if Optional contains a value
w ifPresent(Consumer<T> block)
– executes the given block if a value is present.
w T get()
– returns the value if present; otherwise it throws a
NoSuchElementException.
w T orElse(T default)
– returns the value if present; otherwise it returns a
default value.
w T orElse(Supplier<T> s)
– when empty return the value supplied value by s
Optional<T>
§ Creation uses static factory methods:
w of(T v):
– throw exception if v is null
w ofNullable(T v):
– returns an empty Optional when v is null
w empty()
– returns an empty Optional
w Such methods force the programmer to
think about what he’s about to return

USING COLLECTIONS
Use general interfaces
w E.g. List<> is better than LinkedList<>
§ General interfaces are more flexible
for future changes
§ Makes you think
w First about the type of container
w Then about the implementation

Selecting the container type


§ If access by key is needed use a Map
w If values sorted by key use a SortedMap
§ Otherwise use a Collection
w If indexed access, use a List
– Class depends on expected typical operation
w If access in order, use a Queue
w If no duplicates, use a Set
– If elements sorted, use a SortedSet
Efficiency
§ Time and Space
§ Computed as a function of the number
(n) of elements contained
w Constant: independent of n
w Logarithmic: grows as log(n)
w Linear: grows proportionally to n
w Loglinear: grows as n log(n)
w Quadratic: grows proportionally to n2

Efficiency
20 Quadratic LogLinear
18

16

14

12
Linear
10

4
Logarithmic
2

0 Constant
0 2 4 6 8 10
List implementations
ArrayList LinkedList
§ get(n) § get(n)
w Constant w Linear

§ add(0,…) § add(0, … )
w Linear w Constant

§ add() § add()
w Constant w Constant

57

Linked list
prev
:LinkedList
item "First"
first
next
last
size 2
prev
"Second"
item
next
Linked list
prev
:LinkedList
item "First"
first
next
last
size 3
prev
"Second"
item

prev next

item
"Third"
next

Array list
:ArrayList
0 "First"
elements 1
… "Second"
size 2
8
9
Array list
:ArrayList
0 "First"
elements 1
… "Second"
size 10
8

9
"Tenth"

Array list
:ArrayList 0
0 "First" 1
elements 1 …
… "Second"
size 11 8
8
… 9
9
"Tenth" 10

"Eleventh"

14
List implementations - Get
9000

8000

7000

6000
Time [ns]

5000

4000

3000 LinkedList

2000 ArrayList

1000

0
0 2000 4000 6000 8000 10000

Size [# items]

List Implementations - Add


add in first position in a list of given size
ns
35

30

25

20

15

10 LinkedList

ArrayList
5

0
0 20 40 60 80 100 120 140 160
Size
List Implementations - Add

add given # of elements in first position


9000

8000

7000

6000

5000
LinkedList
4000 ArrayList

3000

2000

1000

0
0 50 100 150 200 250 300

List implementation - Models


LinkedList ArrayList
Add in first pos. t(n) = CL t(n) = n · CA
in list of size n
n
X
Add n elements t(n) = n · CL t(n) = CA · i
i=1
CA
= n · (n 1)
2
CL = 16.0 ns
CA = 0.2 ns
Using maps
§ Getting an item
String val = map.get(key);
if( val == null ) {
// not found
}
§ Or
if( ! map.containsKey(key)) {
// not found
}
String val = map.get(key);

Using maps
§ Updating entries
w E.g. counting frequencies

Map<String,Integer> wc=new XMap<>();


for(String w : words) {
Integer i= wc.get(w);
wc.put(w, i==null?1:i+1);
}
Using maps
§ Updating entries
w E.g. counting frequencies

Map<String,Integer> wc=new XMap<>();


for(String w : words) {
wc.compute(w,(k,v)->v==null?1:v+1);
}
Autoboxing hides memory fee of
16 bytes per increment due to
object creation:
new Integer(v.intValue()+1)

Using maps
§ Updating entries class Counter {
w E.g. counting frequencies } int i=0;

Map<String,Integer> wc=new XMap<>();


for(String w : words) {
wc.computeIfAbsent(w,
k->new Counter()).i++;
}
~40% faster than with Integer
- 16 bytes per each increment
Using maps
§ Keeping items sorted
w Using sorted maps
SortedMap<…> wc=new TreeMap<>();
w “A”=1, “All”=3, “And"=2, “Barefoot”=1,…

Map<…> wc=new HashMap<>();


w “reason”=1, “been”=1, “spoke”=1, “let”=1

HashMap
§ Get/put takes constant time (in case of
no collisions)
§ Automatic re-allocation when load
factor reached
§ Constructor optional arguments
w load factor (default = .75)
w initial capacity (default = 16)

72
Hashmap
:HashMap
0 :Entry "Dog"
buckets 1
… key "domesticated
size 3 carnivorous
e value mammal .."
f
key.hashCode()

:Entry
"Cat" :Entry
key "Pig"
”small key
domesticated value "omnivorous
carnivorous domesticated
mammal"
value hoofed mammal"

Hash limitations
§ Hash based containers HashMap and
HashSet work better if entries define a
suitable hashCode() method
w Values must be as spread as possible
w Otherwise collisions occur
– When two entries fall in the same bucket
– In such a case elements are chained in a list
– Chaining reduces time efficiency
Hashmap (chaining)
:Entry "Dog"
:HashMap
0
buckets 1 key "domesticated
carnivorous
size 3 2 value mammal .."

3 next

:Entry
"Pig"
:Entry
key
"Cat" "omnivorous
key value domesticated
hoofed mammal"
”small
domesticated value next
carnivorous
mammal" next

TreeMap
§ Based on a Red-Black tree
§ Get/put takes log time
§ Keys are maintained and will be
traversed in order
w Key class must be Comparable
w Or a Comparator must be provided to the
constructor

76
TreeMap
:HashMap "Dog"
:Entry
root
key "domesticated
size 3 carnivorous
value mammal .."

left right

:Entry
"Cat" :Entry
key "Pig"
”small key
domesticated value "omnivorous
carnivorous domesticated
mammal"
value hoofed mammal"

Tree limitations
§ Tree based containers (TreeMap and
TreeSet) require either
w Entries with a natural order (Comparable)
w A Comparator to sort entries
§ TreeMap keeps keys sorted, and
return values sorted by key
Search efficiency
§ Example:
w 100k searches in a container require

size HashMap TreeMap ArrayList LinkedList


100k 3ms 60ms 40s >1h

200k 3ms 65ms 110s

ALGORITHMS
Algorithms
§ Static methods of java.util.Collections
w Work on List since it has the concept of position
§ sort() - merge sort of List, n log(n)
§ binarySearch() – requires ordered
sequence
§ shuffle() – unsort
§ reverse() - requires ordered sequence
§ rotate() – of given a distance
§ min(), max() – in a Collection

81

sort() method
§ Operates on List<T>
w Require access by index to perform
sorting
§ Two variants:
<T extends Comparable<? super T>>
void sort(List<T> list)
<T> void sort(List<T> list,
Comparator<? super T> cmp)

82
Sort generic
T extends Comparable<? super T>
MasterStudent Student MasterStudent
§ Why <? super T> instead of just <T> ?
w Suppose you define
– MasterStudent extends Student { }
w Intending to inherit the Student ordering
– It does not implement
Comparable<MasterStudent>
– But MasterStudent extends (indirectly)
Comparable<Student>

83

Search
§ <T> int binarySearch(List<? extends
Comparable<? super T>> l, T key)
w Searches the specified object
w List must be sorted into ascending order
according to natural ordering
§ <T> int binarySearch(List<? extends T> l,
T key, Comparator<? super T> c)
w Searches the specified object
w List must be sorted into ascending order
according to the specified comparator

84
Wrap-up
§ The collections framework includes
interfaces and classes for containers
§ There are two main families
w Group containers
w Associative containers
§ All the components of the framework
are defined as generic types

You might also like