JPII, Session 4
Module 5 - java.util and Collections API
Module4 - Review
Advanced Java / Session4 / 2 of 27
A Guide To Advanced Java – Module 4
2
•
A stream is a logical entity that produces or consumes
information.
•
Data stream supports input/output of primitive data types and
String values.
•
InputStream is an abstract class that defines how data is
received. The OutputStream class is also abstract, it defines the
way in which output is written to streams.
•
File class directly works with files on the file system
•
A buffer is a temporary storage area for data
•
Character streams provide a way to handle character oriented
input/output operations
•
Serialization is the process of reading and writing objects to a byte
stream (Using ObjectInputStream/ObjectOutputStream)
Objectives
Advanced Java / Session4 / 3 of 27
A Guide To Advanced Java – Module 5
Collections are very important
Java Collection API
“If you can program
with Java but you don't understand
interfaces yet, you may have some
trouble getting through the material in
this session.”
“The topics such as linked lists,
queues, stacks, and binary trees,
among many other data structures are
related topic for this session.”
Introduction to java.util package
•
The java.util package contains the definition of a
number of useful classes providing a broad
range of functionality
•
Collections Framework belongs to this package.
It consists of interfaces and classes for working
with group of objects.
Advanced Java / Session4 / 4 of 27
A Guide To Advanced Java – Module 5
Overview of Collection
A collection is a group of data
manipulate as single object.
Corresponds to a b ag.
Can grow as necessary
Heterogeneous
Can be made thread safe (concurrent
access)
Can be made not-modifiable.
Advanced Java / Session4 / 5 of 27
Array vs Collection
Array
o
Holds objects of known type.
o
Fixed size
Collections
o
Generalization of the array concept.
o
Set of interfaces defined in Java for storing
object.
o
Multiple types of objects.
o
Resizable.
Advanced Java / Session4 / 6 of 27
Collection Interfaces
Collections are primarily defined
through a set of interfaces.
Supported by a set of classes that
implement the interfaces
Advanced Java / Session4 / 7 of 27
Some methods of “Collection” interface
-1
Advanced Java / Session4 / 8 of 27
o
int size()
Returns the number of elements in this collection.
o
boolean isEmpty()
Returns true if this collection contains no elements.
o
boolean contains(Object element)
Returns true if this collection contains the specified element
o
boolean add(Object element)
Ensures that this collection contains the specified element
o
Iterator iterator()
Returns an iterator over the elements in this collection.
Iterator -1
An iterator is an object that allows to
traverse through all the elements of a
collection, regardless of its specific
implementation
An iterator is sometimes called a cursor
No need for index
Advanced Java / Session4 / 20 of 27
Iterator - 2
Advanced Java / Session4 / 20 of 27
Collection collection = ;
Iterator it= collection.iterator();
while (it.hasNext()) {
Object element = it.next();
// Do something with element
}
List interface
Advanced Java / Session4 / 10 of 27
A Guide To Advanced Java – Module 5
The List interface is an extension of the
Collection interface.
It defines an ordered collection of data and
allows duplicate objects to be added to a list.
The List interface uses an index for ordering
the elements while storing them in a list. List
has methods that allow access to elements
based on their position.
List interface
Advanced Java / Session4 / 11 of 27
A Guide To Advanced Java – Module 5
Extensions compared to the Collection interface
Access to elements via indexes, like arrays
add (int, Object), get(int), remove(int), set(int, Object)
Search for elements
indexOf(Object), lastIndexOf(Object)
Specialized
Iterator, call ListIterator
Extraction of sublist
subList(int fromIndex, int toIndex)
ArrayList
Advanced Java / Session4 / 11 of 27
A Guide To Advanced Java – Module 5
Implements List interface
cannot store primitive values such as double
Its size increases automatically.
Is best suited for random access without add and
remove operations
ArrayList
•
Demo ArrayListExample
Advanced Java / Session4 / 11 of 27
A Guide To Advanced Java – Module 5
Vector
Advanced Java / Session4 / 11 of 27
A Guide To Advanced Java – Module 5
The Vector class is similar to an ArrayList as it also
implements dynamic array
The difference between Vector and ArrayList class is
that the methods of Vector are synchronised and are
thread-safe. This increases the overhead cost of
calling these methods
LinkedList
Advanced Java / Session4 / 12 of 27
A Guide To Advanced Java – Module 5
LinkedList implements the List interface.
•
addFirst(E obj)
•
addLast(E obj)
•
getFirst()
•
getLast()
•
removeFirst()
•
removeLast()
Gives better performance on add and remove vs
ArrayList
Gives poorer performance on get and set vs ArrayList
Set interface
Advanced Java / Session4 / 21 of 27
A Guide To Advanced Java – Module 5
Corresponds to the mathematical definition
of a set
o
The Set interface creates a list of unordered objects.
o
No duplicates are allowed
Compared to the Collection interface
o
Interface is identical.
o
Every constructor must create a collection without duplicates.
o
The operation add cannot add an element already in the set.
o
The method call set1.equals(set2) works at follows
Set classes
HashSet class implements the Set interface, a
HashSet creates a collection that makes use of a
hash table for data storage
LinkHashSet class creates a list of elements and
maintains the order of elements added to the Set
TreeSet class implements the Set interface and
uses the tree structure for data storage. Objects
are stored in ascending order
Advanced Java / Session4 / 22 of 27
A Guide To Advanced Java – Module 5
Set Idioms
Advanced Java / Session4 / 23 of 27
Map interface -1
Advanced Java / Session4 / 14 of 27
A Guide To Advanced Java – Module 5
A Map is an object that maps keys to values, a map
cannot contain duplicate keys
Map interface -2
Advanced Java / Session4 / 15 of 27
Methods for adding and deleting
o
put(Object key, Object value)
o
remove (Object key)
Methods for extraction objects
o
get (Object key)
Methods to retrieve the keys, the values, and
(key, value) pairs
o
keySet() // returns its set of keys
o
values() // returns a Collection of values
o
entrySet() // returns a set of entry
Map classes
•
HashMap implememts Map.
•
Hashtable class stores elements as a key/value pairs in
the hash table
•
TreeMap class stores elements as tree structure and
returns keys in sorted order. Important methods of the
TreeMap class are firstKey(), lastKey(), headMap(),
tailMap()
•
LinkedHashMap class implements the concept of hash
table and the linked list in the Map interface. Important
methods of the LinkedHashMap class are clear(),
containsValue(), get(), removeEldesEntry()
Advanced Java / Session4 / 16 of 27
A Guide To Advanced Java – Module 5
HashTable
Advanced Java / Session4 / 17 of 27
Map map = new HashMap();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
//tra ve tap key luu trong tap Set
Set keySet = map.keySet();
for (Object key: keySet) {
//lay ve tung value theo key
Object value = map.get(key);
System.out.println(value);
}
Comparable Interface
Advanced Java / Session4 / 18 of 27
Implement the Comparable interface to make
class instances comparable
class Person implements Comparable {
private int age;
private String firstName;
public int compareTo(Object anotherPerson) throws
ClassCastException {
if (!(anotherPerson instanceof Person))
throw new ClassCastException("A Person object expected.");
int anotherPersonAge = ((Person) anotherPerson).getAge();
return this.age - anotherPersonAge;
}
public int getAge() {
return age;
}
}