DDP2-Pekan10-Generics and Collections
DDP2-Pekan10-Generics and Collections
Pemrograman 2
Topik Pekan 11: Generics and Collections
2
Why Do You Get a Warning?
public class ShowUncheckedWarning {
public static void main(String[] args) {
java.util.ArrayList list =
new java.util.ArrayList();
list.add("Java Programming");
}
}
3
Fix the Warning
public class ShowUncheckedWarning {
public static void main(String[] args) {
java.util.ArrayList<String> list =
new java.util.ArrayList<String>();
`
list.add("Java Programming");
}
}
No compile warning on this line.
4
What is Generics?
• Generics is the capability to parameterize types.
• With this capability, you can define a class or a method with
generic types that can be substituted using concrete types by
the compiler.
• For example you may define a generic stack class that stores
the elements of a generic type. From this generic class, you
may create a stack object for holding strings and a stack object
for holding numbers. Here, strings and numbers are concrete
types that replace the generic type.
5
Why Generics?
The key benefit of generics is to enable errors to be
detected at compile time rather than at runtime.
A generic class or method permits you to specify allowable
types of objects that the class or method may work with.
If you attempt to use the class or method with an
incompatible object, a compile error occurs.
6
Generic Type
package java.lang; package java.lang;
Improves reliability
Compile error
7
Generic ArrayList in JDK 1.5
8
No Casting Needed
ArrayList<Double> list = new ArrayList<>();
list.add(5.5); // 5.5 is automatically converted to new Double(5.5)
list.add(3.0); // 3.0 is automatically converted to new Double(3.0)
Double doubleObject = list.get(0); // No casting is needed
double d = list.get(1); // Automatically converted to double
9
Declaring Generic Classes and Interfaces
GenericStack
10
Generic Methods
public static <E> void print(E[] list) {
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
12
Raw Type and Backward Compatibility
// raw type
ArrayList list = new ArrayList();
13
Raw Type is Unsafe
// Max.java: Find a maximum object
public class Max {
/** Return the maximum between two objects */
public static Comparable max(Comparable o1, Comparable o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
}
WildCardNeedDemo
? unbounded wildcard
? extends T bounded wildcard
? super T lower bound wildcard
AnyWildCardDemo SuperWildCardDemo
16
Generic Types and Wildcard Types
17
Avoiding Unsafe Raw Types
Use
new ArrayList<ConcreteType>()
Instead of
new ArrayList();
TestArrayListNew
18
Erasure and Restrictions on Generics
Generics are implemented using an approach called type
erasure.
19
Compile Time Checking
For example, the compiler checks whether generics is used
correctly for the following code in (a) and translates it into
the equivalent code in (b) for runtime use. The code in (b)
uses the raw type.
(a) (b)
20
Important Facts
It is important to note that a generic class is
shared by all its instances regardless of its
actual generic type.
21
Restrictions on Generics
GenericMatrix
23
UML Class Diagram
Rational
24
Generic Matrices
Objective: This example gives two programs that
utilize the GenericMatrix class for integer matrix
arithmetic and rational matrix arithmetic.
IntegerMatrix TestIntegerMatrix
RationalMatrix TestRationalMatrix
25
Ada Pertanyaan?
❑ Jadi apa sih generics itu?
❑ Buat apa generics, kalau tanpa generics juga bisa?
❑ Memang kalau error nya saat runtime kenapa?
❑ erasure? type nya dihapus?! hmm, jadi buat apa
dong kalau nanti dihapus juga?
Objectives
❑To explore the relationship between interfaces and classes in the Java Collections
Framework hierarchy (§20.2).
❑To use the common methods defined in the Collection interface for operating
collections (§20.2).
❑To use the Iterator interface to traverse the elements in a collection (§20.3).
❑To use a for-each loop to traverse the elements in a collection (§20.3).
❑To explore how and when to use ArrayList or LinkedList to store elements
(§20.4).
❑To compare elements using the Comparable interface and the Comparator
interface (§20.5).
❑To use the static utility methods in the Collections class for sorting, searching,
shuffling lists, and finding the largest and smallest element in collections (§20.6).
❑To develop a multiple bouncing balls application using ArrayList (§20.7).
❑To distinguish between Vector and ArrayList and to use the Stack class for
creating stacks (§20.8).
❑To explore the relationships among Collection, Queue, LinkedList, and
PriorityQueue and to create priority queues using the PriorityQueue class
(§20.9).
❑To use stacks to write a program to evaluate expressions (§20.10).
27
Java Collection Framework hierarchy
28
Java Collection Framework hierarchy,
cont.
Set and List are subinterfaces of Collection.
29
The Collection Interface
30
The List Interface
A list stores elements in a sequential order,
and allows the user to specify where the
element is stored. The user can access the
elements by index.
31
The List Interface, cont.
32
The List Iterator
33
ArrayList and LinkedList
The ArrayList class and the LinkedList class are concrete
implementations of the List interface. Which of the two
classes you use depends on your specific needs. If you
need to support random access through an index
without inserting or removing elements from any place
other than the end, ArrayList offers the most efficient
collection. If, however, your application requires the
insertion or deletion of elements from any place in the
list, you should choose LinkedList. A list can grow or
shrink dynamically. An array is fixed once it is created. If
your application does not require insertion or deletion of
elements, the most efficient data structure is the array.
34
java.util.ArrayList
«interface»
java.util.Collection<E>
«interface»
java.util.List<E>
java.util.ArrayList<E>
35
java.util.LinkedList
«interface»
java.util.Collection<E>
«interface»
java.util.List<E>
java.util.LinkedList<E>
36
Example: Using ArrayList and
LinkedList
This example creates an array list filled
with numbers, and inserts new elements
into the specified location in the list. The
example also creates a linked list from the
array list, inserts and removes the
elements from the list. Finally, the example
traverses the list forward and backward.
TestArrayAndLinkedList Run
37
The Comparator Interface
Sometimes you want to compare the elements of
different types. The elements may not be instances of
Comparable or are not comparable. You can define a
comparator to compare these elements. To do so,
define a class that implements the java.util.Comparator
interface. The Comparator interface has two methods,
compare and equals.
38
The Comparator Interface
public int compare(Object element1, Object element2)
Returns a negative value if element1 is less than
element2, a positive value if element1 is greater than
element2, and zero if they are equal.
GeometricObjectComparator Run
TestComparator
39
The Collections Class
The Collections class contains various static methods for
operating on collections and maps, for creating
synchronized collection classes, and for creating read-
only collection classes.
40
The Collections Class UML Diagram
41
Case Study: Multiple Bouncing Balls
MultipleBounceBall Run
42
The Vector and Stack Classes
43
The Vector Class
44
The Vector Class, cont.
45
The Stack Class
The Stack class represents a last-in-first-
out stack of objects. The elements are
accessed only from the top of the stack.
java.util.Vector<E> You can retrieve, insert, or remove an
element from the top of the stack.
java.util.Stack<E>
46
Queues and Priority Queues
A queue is a first-in/first-out data structure. Elements are
appended to the end of the queue and are removed from
the beginning of the queue. In a priority queue, elements
are assigned priorities. When accessing elements, the
element with the highest priority is removed first.
47
The Queue Interface
48
Using LinkedList for Queue
49
The PriorityQueue Class
PriorityQueueDemo Run
50
Case Study: Evaluating Expressions
Stacks can be used to evaluate expressions.
Evaluate Expression
51
Algorithm
Phase 1: Scanning the expression
The program scans the expression from left to right to extract operands,
operators, and the parentheses.
1.1. If the extracted item is an operand, push it to operandStack.
1.2. If the extracted item is a + or - operator, process all the operators at the
top of operatorStack and push the extracted operator to operatorStack.
1.3. If the extracted item is a * or / operator, process the * or / operators at
the top of operatorStack and push the extracted operator to operatorStack.
1.4. If the extracted item is a ( symbol, push it to operatorStack.
1.5. If the extracted item is a ) symbol, repeatedly process the operators
from the top of operatorStack until seeing the ( symbol on the stack.
52
Example
53
Ada Pertanyaan?
Objectives
❑To store unordered, nonduplicate elements using a set (§21.2).
❑To explore how and when to use HashSet (§21.2.1), LinkedHashSet
(§21.2.2), or TreeSet (§21.2.3) to store elements.
❑To compare performance of sets and lists (§21.3).
❑To use sets to develop a program that counts the keywords in a
Java source file (§21.4).
❑To tell the differences between Collection and Map and describe
when and how to use HashMap, LinkedHashMap, and TreeMap to
store values associated with keys (§21.5).
❑To use maps to develop a program that counts the occurrence of
the words in a text (§21.6).
❑To obtain singleton sets, lists, and maps, and unmodifiable sets,
lists, and maps, using the static methods in the Collections class
(§21.7).
55
Motivations
The “No-Fly” list is a list, created and maintained by the U.S.
government’s Terrorist Screening Center, of people who are not
permitted to board a commercial aircraft for travel in or out of the
United States. Suppose we need to write a program that checks
whether a person is on the No-Fly list. You can use a list to store
names in the No-Fly list. However, a more efficient data structure
for this application is a set.
56
Review of Java Collection Framework
hierarchy
Set and List are subinterfaces of Collection.
57
The Collection interface is the root interface
for manipulating a collection of objects.
58
The Set Interface
The Set interface extends the Collection interface. It does
not introduce new methods or constants, but it stipulates
that an instance of Set contains no duplicate elements.
The concrete classes that implement Set must ensure that
no duplicate elements can be added to the set. That is no
two elements e1 and e2 can be in the set such that
e1.equals(e2) is true.
59
The Set Interface
Hierarchy
60
The AbstractSet Class
The AbstractSet class is a convenience class that extends
AbstractCollection and implements Set. The AbstractSet
class provides concrete implementations for the equals
method and the hashCode method. The hash code of a
set is the sum of the hash code of all the elements in the
set. Since the size method and iterator method are not
implemented in the AbstractSet class, AbstractSet is an
abstract class.
61
The HashSet Class
The HashSet class is a concrete class that
implements Set. It can be used to store
duplicate-free elements. For efficiency,
objects added to a hash set need to
implement the hashCode method in a
manner that properly disperses the hash
code.
62
Example: Using HashSet and Iterator
TestHashSet Run
63
TIP: for-each loop
You can simplify the code in Lines 21-26 using a JDK 1.5
enhanced for loop without using an iterator, as follows:
64
Example: Using LinkedHashSet
This example creates a hash set filled with
strings, and uses an iterator to traverse the
elements in the list.
TestLinkedHashSet Run
65
The SortedSet Interface and the
TreeSet Class
SortedSet is a subinterface of Set, which
guarantees that the elements in the set are
sorted. TreeSet is a concrete class that
implements the SortedSet interface. You can
use an iterator to traverse the elements in
the sorted order. The elements can be
sorted in two ways.
66
The SortedSet Interface and the
TreeSet Class, cont.
One way is to use the Comparable interface.
67
Example: Using TreeSet to Sort
Elements in a Set
This example creates a hash set filled with strings, and
then creates a tree set for the same strings. The strings
are sorted in the tree set using the compareTo method
in the Comparable interface. The example also creates
a tree set of geometric objects. The geometric objects
are sorted using the compare method in the
Comparator interface.
TestTreeSet Run
68
Example: The Using Comparator to Sort
Elements in a Set
Write a program that demonstrates how to
sort elements in a tree set using the
Comparator interface. The example creates
a tree set of geometric objects. The
geometric objects are sorted using the
compare method in the Comparator
interface.
TestTreeSetWithComparator Run
69
Performance of Sets and Lists
SetListPerformanceTest Run
70
Case Study: Counting Keywords
CountKeywords Run
71
The Map Interface
The Map interface maps keys to the elements. The keys
are like indexes. In List, the indexes are integer. In Map,
the keys can be any objects.
72
Map Interface and Class Hierarchy
An instance of Map represents a group of objects, each of
which is associated with a key. You can get the object
from a map using a key, and you have to use a key to put
the object into the map.
73
The Map Interface UML Diagram
74
Concrete Map Classes
75
Entry
76
HashMap and TreeMap
The HashMap and TreeMap classes are two
concrete implementations of the Map
interface. The HashMap class is efficient for
locating a value, inserting a mapping, and
deleting a mapping. The TreeMap class,
implementing SortedMap, is efficient for
traversing the keys in a sorted order.
77
LinkedHashMap
LinkedHashMap was introduced in JDK 1.4. It extends
HashMap with a linked list implementation that supports
an ordering of the entries in the map. The entries in a
HashMap are not ordered, but the entries in a
LinkedHashMap can be retrieved in the order in which
they were inserted into the map (known as the insertion
order), or the order in which they were last accessed, from
least recently accessed to most recently (access order).
The no-arg constructor constructs a LinkedHashMap with
the insertion order. To construct a LinkedHashMap with
the access order, use the LinkedHashMap(initialCapacity,
loadFactor, true).
78
Example: Using HashMap and
TreeMap
TestMap Run
79
Case Study: Counting the
Occurrences of Words in a Text
This program counts the occurrences of words in a text and
displays the words and their occurrences in ascending order
of the words. The program uses a hash map to store a pair
consisting of a word and its count. For each word, check
whether it is already a key in the map. If not, add the key and
value 1 to the map. Otherwise, increase the value for the
word (key) by 1 in the map. To sort the map, convert it to a
tree map.
CountOccurrenceOfWords Run
80
The Singleton and Unmodiable Collections
81
Selamat Berlatih!
Perhatikan lagi List Objective yang perlu dikuasai
pekan ini.
Baca buku acuan dan berlatih!
Bila masih belum yakin tanyakan ke dosen,
tutor atau Kak Burhan.
Semangat !