session3 - Advanced Java 2

Download Report

Transcript session3 - Advanced Java 2

Advanced Java
Session 3
New York University
School of Continuing and Professional Studies
Objectives
• Backlog - jar, Synchronized keyword and
Class Constructors
• Collection Interfaces
• Concrete Collections
• Collection Framework
• Algorithms
• Legacy Collections
2
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.
3
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
4
Queue Example
Interface Queue
{
void add(Object obj);
Object remove();
int size();
}
1
2
head
3
4
tail
5
Circular Array Implementation
9
10
tail
6
7
8
head
6
Linked List Implementation
1
head
2
3
4
tail
7
Sort program
import java.util.*;
public class sort {
public static void main(String args[]) {
List l = Arrays.asList(args);
Collections.sort(l);
System.out.println(l);
}
}
8
Collection Interface
• Has three fundamental methods
– boolean add (Object obj)
– boolean remove (Object obj)
– Iterator iterator()
• Other methods
–
–
–
–
–
boolean
boolean
boolean
boolean
boolean
contains(Object obj)
size()
isEmpty()
retainAll(Collection c)
containsAll(Collection c)
9
Iterator Interface
• Has three fundamental methods
– Object next()
– boolean hasNext()
– void remove()
Element
1
Element
2
Element
3
Element
4
Element
5
next()
10
Concrete Collections
•
•
•
•
•
•
•
LinkedList
ArrayList
HashSet
TreeSet
EnumSet
LinkedHashSet
PriorityQueue
•
•
•
•
•
HashMap
TreeMap
EnumMap
LinkedHashMap
WeakHashMap
11
LinkedList
Head
Data – elem1
Next
Previous
Data – elem2
Next
Previous
Data – elem3
Next
Previous
Null
Null
Data – new
Next
Previous
12
An example of LinkedList
public class LinkedListExample {
public static void main(String args[]) {
LinkedList staff = new LinkedList();
staff.add(“Bob”); staff.add(“Angela”);
staff.add(“John”);
ListIterator iter = staff.iterator();
while( iter.hasNext() ) { System.out.println(iter.next()); }
while( iter.hasPrevious() ) { System.out.println(iter.previous()); }
System.out.println(staff.get(2));
}
}
13
ArrayList
• Similar to a Vector
• Methods of ArrayList are not synchronized
• Methods of Vector are synchronized
14
HashSet
• Implements a “hash table” data structure
• Can supply initial capacity
• Class must provide hashCode() method
10
20
14
17
19
33
30
40
42
45
15
TreeSet
• Similar to HashSet, except it sorts the values as
you insert, and when you traverse the values,
they are presented back in a sorted order.
10
20
14
17
19
33
30
40
42
45
16
HashMap
• Implements a data structure to store key,value
pairs
• Entries are indexed by unique key
14v
10k
20k
14k
17v
17k
42v
19v
19k
45v
30k
40k
42k
45k
17
TreeMap
• Sorts the keys
• Comparison is applied to keys – not values
14v
10k
20k
14k
17v
17k
42v
19v
19k
45v
30k
40k
42k
45k
18
An example of Map
public class MapTest
{ public static void main(String[] args)
{ Map staff = new HashMap();
staff.put("144-25-5464", new Employee("Angela Hung"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
19
An example of Map
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
20
An example of Map
// iterate through all entries
Set entries = staff.entrySet();
Iterator iter = entries.iterator();
while (iter.hasNext())
{ Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println("key=" + key + ", value=" + value);
}
}
}
21
Algorithms/Utility methods in
Collections 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
22
Algorithms/Utility methods in
Collections 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
23
Legacy Collections
•
•
•
•
Vector
Hashtable
Enumeration
Properties
24
TradeProcessor Examples
TradeProcessor1 through TradeProcessor11
25
TradeProcessor3
Using collections of Custom classes – ArrayList<Trade>
Your custom class must implement “Comparable”
if you want to use Collections.sort method to sort
a collection of your class objects
Example: TradeProcessor4
26
TradeProcessor5
Using custom Comparator to sort
Your custom class must implement “Comparable”
if you want to use Collections.sort method to sort
a collection of your class objects
27
TradeProcessor6
Removing Duplicates using HashSet
28
TradeProcessor7
Removing Duplicates using HashSet
Your custom class must implement hashCode and
equals methods in order to be added to HashSet
29
HashSet uses hashCode and equals
TradeProcessor
HashSet
add(t)
Trade
t.hashCode()
Hash value x
If (bucket x not empty)
If any of the calls to
equals returns true, then
duplicate is not added
and “false” is returned
else item is added and
“true is returned
for each s in bucket x
s.equals(t)
True/false
30
hashCode and equals
• If two objects are equal, they MUST have matching
hashcode
• If two objects are equal, calling equals() on either object
MUST return true (if a.equals(b), then b.equals(a) must be
true)
• If two objects have the same hashcode value, they are NOT
required to be equal. But if they are equal, they MUST
have the same hashcode value.
• So, if you override equals, you MUST override hashCode
• The default behavior of hashCode is to generate a unique
integer based on its memory address
• The default behavior of equals is to do an = = comparison.
31
Generics
• Create type-safe Collections
• More problems may be caught at compile
time rather than at run time
• For example – without generics any
collection can keep anything of type
“Object” and when you get it back from the
collection you have to “cast” it to your type.
32
Using Generics
new ArrayList<Trade>
List<Trade> tradeList = new
ArrayList<Trade>
void cancelTrades(List<Trade>)
tp.cancelTrades(tradeList);
33
Writing Generics
pulic class ArrayList<E> extends
AbstractList<E> implements List<E> …
public boolean add(E o)
34
Type Parameter
ArrayList<Trade> tradeList = new
ArrayList<Trade>
pulic class ArrayList<E> extends
AbstractList<E> implements List<E> … {
public boolean add(E o)
pulic class ArrayList<Trade> extends
AbstractList<Trade> … {
public boolean add(Trade o)
35
Type Parameter
pulic class ArrayList<E> extends
AbstractList<E> implements List<E> … {
public boolean add(E o)
pulic class TradeProcessor {
public <T extends Trade>
cancelTrades(ArrayList<T> trades);
36
Type Parameter
pulic class TradeProcessor {
public <T extends Trade>
cancelTrades(ArrayList<T> trades);
pulic class TradeProcessor {
public cancelTrades(ArrayList<Trade>
trades);
37
Arrays vs Generics
TestArrays.java
TestArrays2.java
TestGenerics1.java
TestGenerics2.java
TestGenerics3.java
TestGenerics4.java
38
Type Checking in Generics
• Array types are checked again at runtime but collection
type checks are done only when you compile.
39