0% found this document useful (0 votes)
58 views82 pages

DDP2-Pekan10-Generics and Collections

Generics and Collections were the topics for Week 11. The objectives were to understand generics by using generic classes and interfaces, declaring generic types, and understanding why generics improve reliability. It also covered using wildcard types, converting legacy code to use generics, and restrictions due to type erasure. The topics also included understanding the Java Collections Framework hierarchy and using common Collection methods, iterators, and for-each loops to traverse collections as well as comparing elements using Comparable and Comparator.

Uploaded by

Reva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views82 pages

DDP2-Pekan10-Generics and Collections

Generics and Collections were the topics for Week 11. The objectives were to understand generics by using generic classes and interfaces, declaring generic types, and understanding why generics improve reliability. It also covered using wildcard types, converting legacy code to use generics, and restrictions due to type erasure. The topics also included understanding the Java Collections Framework hierarchy and using common Collection methods, iterators, and for-each loops to traverse collections as well as comparing elements using Comparable and Comparator.

Uploaded by

Reva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Dasar Dasar

Pemrograman 2
Topik Pekan 11: Generics and Collections

Acuan: Introduction to Java Programming and Data


Structure, Bab 19, 20 dan 21
Sumber Slide: Y Daniel Liang, Introduction to Java
Programming and Data Structure, Pearson.
Dimodifikasi untuk Fasilkom UI oleh Ade Azurat dan
Muhammad Hilman
Objectives
❑To know the benefits of generics (§19.1).
❑To use generic classes and interfaces (§19.2).
❑To declare generic classes and interfaces (§19.3).
❑To understand why generic types can improve reliability and readability
(§19.3).
❑To declare and use generic methods and bounded generic types (§19.4).
❑To use raw types for backward compatibility (§19.5).
❑To know wildcard types and understand why they are necessary (§19.6).
❑To convert legacy code using JDK 1.5 generics (§19.7).
❑To understand that generic type information is erased by the compiler and
all instances of a generic class share the same runtime class file (§19.8).
❑To know certain restrictions on generic types caused by type erasure
(§19.8).
❑To design and implement generic matrix classes (§19.9).

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");
}
}

Type safety: The method add(Object) To understand the compile


belongs to the raw type ArrayList.
References to generic type ArrayList<E>
warning on this line, you need to
should be parameterizedJava(16777747) learn JDK 1.6 generics.

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;

public interface Comparable { public interface Comparable<T> {


public int compareTo(Object o) public int compareTo(T o)
} }

(a) Prior to JDK 1.5 (b) JDK 1.5

Runtime error Generic Instantiation


Comparable c = new Date(); Comparable<Date> c = new Date();
System.out.println(c.compareTo("red")); System.out.println(c.compareTo("red"));

(a) Prior to JDK 1.5 (b) JDK 1.5

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();
}

public static void print(Object[] list) {


for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
11
Bounded Generic Type
public static void main(String[] args ) {
Rectangle rectangle = new Rectangle(2, 2);
Circle circle = new Circle (2);
System.out.println("Same area? " + equalArea(rectangle, circle));
}

public static <E extends GeometricObject> boolean


equalArea(E object1, E object2) {
return object1.getArea() == object2.getArea();
}

12
Raw Type and Backward Compatibility
// raw type
ArrayList list = new ArrayList();

// This is roughly equivalent to

ArrayList<Object> list = new ArrayList<Object>();

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;
}
}

Max.max("Welcome", 23); Runtime Error!


14
Make it Safe
// Max1.java: Find a maximum object
public class Max1 {
/** Return the maximum between two objects */
public static <E extends Comparable<E>> E max(E o1, E o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
} Compile Time Error!
Max.max("Welcome", 23); Lebih baik, karena Programmer bisa
tahu dan memperbaiki lebih awal!
15
Wildcards
Why wildcards are necessary? See this example.

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.

The compiler uses the generic type information to compile


the code, but erases it afterwards.

So the generic information is not available at run time.

This approach enables the generic code to be backward-


compatible with the legacy code that uses raw types.

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.

ArrayList<String> list = new ArrayList<>(); ArrayList list = new ArrayList();


list.add("Oklahoma"); list.add("Oklahoma");
String state = list.get(0); String state = (String)(list.get(0));

(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.

GenericStack<String> stack1 = new GenericStack<>();


GenericStack<Integer> stack2 = new GenericStack<>();

Although GenericStack<String> and GenericStack<Integer>


are two types, but there is only one class GenericStack
loaded into the JVM.

21
Restrictions on Generics

❑Restriction 1: Cannot Create an Instance of a Generic


Type. (i.e., new E()).

❑Restriction 2: Generic Array Creation is Not Allowed.


(i.e., new E[100]).

❑Restriction 3: A Generic Type Parameter of a Class Is Not


Allowed in a Static Context.

❑Restriction 4: Exception Classes Cannot be Generic.


22
Designing Generic Matrix Classes
Objective: This example gives a generic class for
matrix arithmetic. This class implements matrix
addition and multiplication common for all types of
matrices.

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

A collection is a container object that holds


a group of objects, often referred to as
elements. The Java Collections Framework
supports three types of collections, named
lists, sets, and maps.

28
Java Collection Framework hierarchy,
cont.
Set and List are subinterfaces of Collection.

29
The Collection Interface

The Collection interface is the root interface for manipulating a


collection of objects.

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>

+ArrayList() Creates an empty list with the default initial capacity.


+ArrayList(c: Collection<? extends E>) Creates an array list from an existing collection.
+ArrayList(initialCapacity: int) Creates an empty list with the specified initial capacity.
+trimToSize(): void Trims the capacity of this ArrayList instance to be the
list's current size.

35
java.util.LinkedList
«interface»
java.util.Collection<E>

«interface»
java.util.List<E>

java.util.LinkedList<E>

+LinkedList() Creates a default empty linked list.


+LinkedList(c: Collection<? extends E>) Creates a linked list from an existing collection.
+addFirst(o: E): void Adds the object to the head of this list.
+addLast(o: E): void Adds the object to the tail of this list.
+getFirst(): E Returns the first element from this list.
+getLast(): E Returns the last element from this list.
+removeFirst(): E Returns and removes the first element from this list.
+removeLast(): E Returns and removes the last element from this list.

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

The Java Collections Framework was introduced with


Java 2. Several data structures were supported prior to
Java 2. Among them are the Vector class and the Stack
class. These classes were redesigned to fit into the Java
Collections Framework, but their old-style methods are
retained for compatibility. This section introduces the
Vector class and the Stack class.

43
The Vector Class

In Java 2, Vector is the same as ArrayList, except that


Vector contains the synchronized methods for
accessing and modifying the vector. None of the new
collection data structures introduced so far are
synchronized. If synchronization is required, you can
use the synchronized versions of the collection classes.
These classes are introduced later in the section, “The
Collections 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>

+Stack() Creates an empty stack.


+empty(): boolean Returns true if this stack is empty.
+peek(): E Returns the top element in this stack.
+pop(): E Returns and removes the top element in this stack.
+push(o: E) : E Adds a new element to the top of this stack.
+search(o: Object) : int Returns the position of the specified element in this stack.

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.

Phase 2: Clearing the stack


Repeatedly process the operators from the top of operatorStack until
operatorStack is empty.

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.

Suppose your program also needs to store detailed information


about terrorists in the No-Fly list. The detailed information such as
gender, height, weight, and nationality can be retrieved using the
name as the key. A map is an efficient data structure for such a task.

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

This example creates a hash set filled with


strings, and uses an iterator to traverse the
elements in the list.

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:

for (Object element: set)


System.out.print(element.toString() + " ");

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.

The other way is to specify a comparator for the


elements in the set if the class for the elements does not
implement the Comparable interface, or you don’t want
to use the compareTo method in the class that
implements the Comparable interface. This approach is
referred to as order by comparator.

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

This section presents an application that counts the


number of the keywords in a Java source file.

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

This example creates a hash map that maps


borrowers to mortgages. The program first
creates a hash map with the borrower’s
name as its key and mortgage as its value.
The program then creates a tree map from
the hash map, and displays the mappings in
ascending order of the keys.

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 !

You might also like