Upload
bruce-douglas
View
214
Download
2
Embed Size (px)
Citation preview
Advanced JavaSession 3
New York University
School of Continuing and Professional Studies
2
Objectives
• Revisit thread Synchronization issues– Updated versions of SynchBankTest and
UnsynchBankTest
• Collection Interfaces• Concrete Collections• Collection Framework• Algorithms• Legacy Collections
3
Synchronization Issues
• Race condition – producer-consumer– When multiple threads try to manipulate the same object,
they may get wrong results.
• Deadlock – dining philosophers– A thread going after a resource that’s held by another
thread, while the other thread needs the resource held by this thread, hence both wait endlessly.
4
Synchronization Examples
• UnsynchBankTest.java– TransferThread– TestThread
• SynchBankTest.java– TransferThread– TestThread
5
Interfaces
• You cannot instantiate an object of type Interface with new.
• You can declare that an object variable will be of that interface type.
• You can use “instanceof” to check if an object implements an interface.
• You cannot put instance fields, or static methods in interfaces.
• You can put constants in interfaces.
6
Implementations
• A class may implement one or more Interfaces using the keyword “implements”
-----
public interface Comparable
{
public int compareTo(Object b)
}
------
Class Employee extends Person implements Comparable
7
Queue Example
1 2 3 4
head tail
Interface Queue{
void add(Object obj);Object remove();int size();
}
8
Circular Array Implementation
head
tail
910
678
9
Linked List Implementation
head tail
1 2 3 4
10
Sort programimport java.util.*;
public class sort { public static void main(String args[]) { List l = Arrays.asList(args); Collections.sort(l); System.out.println(l); }}
11
Collection Interface
• Has three fundamental methods– boolean add (Object obj)– boolean remove (Object obj)– Iterator iterator()
• Other methods– boolean contains(Object obj)– boolean size()– boolean isEmpty()– boolean retainAll(Collection c)– boolean containsAll(Collection c)
12
Iterator Interface
• Has three fundamental methods– Object next()– boolean hasNext()– void remove()
Element1
Element2
Element3
Element4
Element5
next()
13
Concrete Collections
• Linked Lists
• Array Lists
• Hash Sets
• Tree Sets
• Maps
• Week Hash Maps
10
20
30
40
14 17 19
33
42 45
14
Algorithms/Utility methods inCollections class
• Common set of methods that work on all types of Collections and Lists
• min, max – can work on any Collection
• sort, binarySearch, shuffe, reverse, copy, fill – can work on any List
• unmodifiable and synchronized versions of Collections
15
Legacy Collections
• Hashtable
• Enumeration
• Properties