Académique Documents
Professionnel Documents
Culture Documents
hashCode() !
equals()"
Supplementary Objectives
# $ %
Collection&Set&SortedSet&List&Map&SortedMap
'
' $ addAll()&removeAll()&
retainAll() Collection
( ) *
'
# $
% HashSet&TreeSet&LinkedHashSet&ArrayList&Vector&LinkedList&
HashMap&Hashtable&TreeMap&LinkedHashMap
'
& &
' $ Comparable
$ Comparator
, UnsupportedOperationException $
# $ Collections
* $
, - $ Collections
+ $
/ -
$
java.util %
$
! 0 111 111"
$ 2 $ 2
.
& & )
Core Interfaces
Collection ) &
$ 0 111
) 111
Collection .
-
Set Set 2 Collection HashSet
% LinkedHashSet
Implementations
java.util * $ &
0 113 114
5
$ Collection
$ &
Collection -
$ $
$ Map
5 !
" $ - & -
&
$ & $ $ $
- & $
. $ 113
!
# "
" %
$
&
HashSet Set ' 5 equals() 8
hashCode()
11.2 Collections
Collection ,
& $
UnsupportedOperationException
java.util
Collection ! 0 113 113"
$ boolean
Basic Operations
$
int size()
boolean isEmpty()
boolean contains(Object element)
boolean add(Object element) // Optional
boolean remove(Object element) // Optional
$ false& add() 2
& $ -
-
contains() -
- $
Bulk Operations
boolean containsAll(Collection c)
boolean addAll(Collection c) // Optional
boolean removeAll(Collection c) // Optional
boolean retainAll(Collection c) // Optional
void clear() // Optional
addAll()&removeAll()& retainAll()
$ $
) $: 0 11;
' & #
Array Operations
$
Object[] toArray()
Object[] toArray(Object a[])
toArray() $
$ $
# $ & $#
$& & $
& null $ #
$ & $ $ )
# $ $ $ $
$ & ArrayStoreException
Iterators
. .
$ Collection %
Iterator iterator()
( - Iterator
Iterator %
boolean hasNext()
( true $ .
next() 2
Object next()
2 $ &
# &
NoSuchElementException
Object remove()
( $ next() &
$ # IllegalStateException&
next() $ & remove() $
next() &
& UnsupportedOperationException
. & $ Iterator
$ $ $ $ 62 111
$( )
import java.util.*;
< %
62 111
1 1=& 2 ArrayList , int
- & $ & int
Integer - &
Collection $ - +
& $ Object < & $
- $ *
toString() 2
2 $ toString()
[ , , ..., ]
2 $ toString()
. !3" !
>" toString()
$ 2
# 62 111& !
4" !
;"
2 !
?" #
instanceof $ -
+ 2
$Integer
5 & $
& 62 111
- $ java.util +
$ & $ $ $ $
,
ConcurrentModificationException remove() $
$ $
$
$ 0 2 &
$ &
$ .
Review Questions
+ @
Set
Bag
LinkedList
Collection
Map
+ $ java.util @
HashList
HashMap
ArraySet
ArrayMap
TreeMap
+ *
@
Collection
Set
SortedSet
List
Sequence
11.3 Sets
' Collection & Set
null
Set $ & add() addAll()
# $ & add()
true& false . Set !
114"
& & -
! " Set
& # *
+ , #
a.containsAll(b) b a! "
a.addAll(b) a = a b! "
a.removeAll(b) a = a – b! "
a.retainAll(b) a = a b! "
a.clear() a = C! $ "
LinkedHashSet HashSet
! & " ! &
$"
HashSet()
B & $
HashSet(Collection c)
B
$ $
HashSet(int initialCapacity)
B & $ $
B & $ $
$( )
import java.util.*;
if (areDisjunct)
System.out.println(characters + " and " + encountered +
" are disjunct.");
else {
// Determine superset and subset relations. (5)
boolean isSubset = encountered.containsAll(characters);
boolean isSuperset = characters.containsAll(encountered);
if (isSubset && isSuperset)
System.out.println(characters + " is equivalent to " +
encountered);
else if (isSubset)
System.out.println(characters + " is a subset of " +
encountered);
else if (isSuperset)
System.out.println(characters + " is a superset of " +
encountered);
else
System.out.println(characters + " and " +
encountered + " have " + commonSubset + " in common.");
}
( %
62 113 #
%
$ - & &
$ & &
D &
&
encountered !1" 0 & &
!3" & characters&
& !4"
& !
;"%
5 retainAll() !
;"
encountered characters # ) ) &
- 7 &
!?" containsAll()
# $ & &
2 & $ $
$ addAll()
& !
A"%
encountered.addAll(characters); // (6)
2 $ toString()
AbstractSet HashSet ! 0 113"
11.4 Lists
&
6 & & .) *
2 $ 2
( 2
( 2 #
2
# 2# $&
$ 2 $
add(Object) Collection
2& $
remove(Object) Collection
# 2&
true $
# * $ & 20 size()-1 .
2 & IndexOutOfBoundsException 2
// Element Search
int indexOf(Object o)
int lastIndexOf(Object o)
$ 2
7 & E1
// List Iterators
ListIterator listIterator()
ListIterator listIterator(int index)
$&
&
$ 2
boolean hasNext();
boolean hasPrevious();
ListIterator # 2 Iterator
+ &
// Open Range-View
List subList(int fromIndex, int toIndex)
&
2fromIndex 2toIndex-1 .
$ .$ $
& :
LinkedList& Vector
LinkedList $* # $*
$ F & $ LinkedList
2 & &
LinkedList%
ArrayList %
ArrayList()
B & $ArrayList . $
LinkedList Vector
ArrayList(Collection c)
B ArrayList
ArrayList $ ArrayList $
.
$ LinkedList Vector
ArrayList(int initialCapacity)
B & $ArrayList $.
$ Vector
$( ) *
import java.util.*;
( %
java TakeAGuess 3 2 2 2 7
62 114 *
* 2 &
String - secretSolution !
1"
add() &
guess& !
3"
$ !
4"
guess . 2
$ get() remove() true
& &
0 $ $ &
guess secretSolution %
Review Questions
' + @
, $
UnsupportedOperationException
UnsupportedOperationException throws
. List
. ArrayList $ 2
Collection get
- + @
import java.util.*;
set1.removeAll(list1);
list1.addAll(set2);
list2.addAll(list1);
set1.removeAll(list2);
System.out.println(set1);
}
static void addRange(Collection col, int step) {
for (int i = step*2; i<=25; i+=step)
col.add(new Integer(i));
}
}
TreeSet $set2
Comparator
&
UnsupportedOperationException
3?
. + Collection @
add(Object o)
retainAll(Collection c)
get(int index)
iterator()
indexOf(Object o)
/ + @
import java.util.*;
public class Iterate {
public static void main(String[] args) {
List l = new ArrayList();
l.add("A"); l.add("B"); l.add("C"); l.add("D"); l.add("E");
ListIterator i = l.listIterator();
i.next(); i.next(); i.next(); i.next();
i.remove();
i.previous(); i.previous();
i.remove();
System.out.println(l);
};
};
# [A, B, C, D, E].
# [A, C, E].
# [B, D, E].
# [A, B, D].
# [B, C, E].
# NoSuchElementException
0 + Collection true
@
contains()
add()
containsAll()
retainAll()
clear()
11.5 Maps
. Map $ G H .
$& & $ 6 $
& &
$ 0 2 & * & ! "
$ ! $"
& $
$ -
- & $
. Map 2 Collection
8 & $% $ & &
$ $
Map #
UnsupportedOperationException $
java.util Map !
113 0 114"
Basic Operations
$ $
# Gkey&valueH $ # $
$& $< & null
( $ & null $
remove() $ $#
$ $& $< & null
( true $
( true 2 $
int size()
boolean isEmpty()
! & $ "
Bulk Operations
&
Collection Views
Set keySet()
Collection values()
Set entrySet()
B
& $&
G H & $5 Collection
$ values() Set& $ & &
6 G H
$ $ - Map.Entry
. $ $ $ &
* 2 $%
interface Entry {
Object getKey();
Object getValue();
Object setValue(Object value);
}
< $
hashCode() equals() $ - ! , 11>& ;A1"
LinkedHashMap HashMap
LinkedHashMap HashMap
LinkedHashSet HashSet 6 HashMap ! HashSet"
LinkedHashMap ! LinkedHashSet" $ &
LinkedHashMap & & $
$ * & $
$J $ $ 2 LinkedHashSet
! " 8 & LinkedHashMap ! "
& & & * $
* $
LinkedHashMap
toString() 2
$ toString()
{ = , = , ..., = }
2 $ toString()
$ - & $
. &
$ & 2
$ $ HashMap
%
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
B & $HashMap& $
HashMap(Map otherMap)
LinkedHashMap Hashtable
HashMap # & LinkedHashMap
%
$( ')
import java.util.*;
/* Create a list of groups (keys), and use the sort algorithm from
the Collections class to sort the keys. */
List keys = new ArrayList(groupFreqData.keySet()); // (4)
Collections.sort(keys); // (5)
( %
10: *
60: *
75: ***
80: *
90: *
95: **
185: *
62 11; 2 $
&
2 & $ &
%
# &
$ %
!
1" & $&
!
3"& & !
4" , $ & $
$
# $ ! " groupFreqData
keySet() $& &
!
;" $ $ sort() Collections &
!
?"
# $& $ groupFreqData
. $
!
A"
!
I"
+ J Comparable Comparator&
/ $ )
. Comparator &
%
. $ Comparable
$ L ./#& &String&Date& File&
java.lang.Comparable %
int compareTo(Object o)
&) & -
& & - & #
ClassCastException
$ - , $&
equals()
! , 11>"
< -
$ Collections.sort()
- $
$ ! , 1=4& 4KA" . &
$ & -
. $ Comparator
Collections Arrays
$ & Comparator ! , 11I& ;I3"
62 11?
$ TreeSet ! "6
!
3" . 2
!
4"
String !
CASE_INSENSITIVE_ORDER"
- compare() 2 $
!
1"
$ & *
+ # $ &
$ 2
& 0
& & 0 2 &
"report" "court"& B
& 'o' 'u'
. $ & "report"
"court"
B $
2 $# &"report"
"court"& "troper" 2 $ "truoc"
. $ $ RhymingStringComparator 62
11? compare() !
;"
. &
& !
?" compare()
compareTo() !
A" & 2
$
!
1"
$ & $
$( -1 # #
import java.util.*;
// Choice of comparator.
// Set strSet = new TreeSet(); // (1a)
// Set strSet = new TreeSet(String.CASE_INSENSITIVE_ORDER); // (1b)
Set strSet = new TreeSet(new RhymingStringComparator()); // (1c)
>java ComparatorUsage court Stuart report Resort assort support transport distort
< !
1"%
< !
1"%
< $ !
1"%
// Range-view operations
SortedSet headSet(Object toElement)
SortedSet tailSet(Object fromElement)
SortedSet subSet(Object fromElement, Object toElement)
headSet() &
$ , $& tailSet()
&
subSet() &
fromElement& & toElement& 2 5
$
// First-last elements
Object first()
Object last()
// Comparator access
Comparator comparator()
& null
& & $
& $
// Range-view operations
SortedMap headMap(Object toKey)
SortedMap tailMap(Object fromKey)
SortedMap subMap(Object fromKey, Object toKey)
// First-last keys
Object firstKey()
Object lastKey()
// Comparator access
Comparator comparator()
& 2
, HashSet HashMap TreeSet TreeMap&
$
6 %
TreeSet()
TreeMap()
. $ &
$& $
TreeSet(Comparator c)
TreeMap(Comparator c)
. 2 $
TreeSet(Collection c)
TreeMap(Map m)
. &
$& $
TreeSet(SortedSet s)
TreeMap(SortedMap m)
.
&
$( .)
import java.util.*;
/* Only the histogram for the weight groups between 50 and 150
is of interest. Print frequency for these groups in a sorted order. */
( %
60: *
75: ***
80: *
90: *
95: **
62 11A # 2 62
11;&
%
( &
$ 62 11;
& !
;"
B & !
?"
' , & !
A" 0 &
entrySet() ! & "
& $ .
Iterator entryIterator =
selectedGroupFreqData.entrySet().iterator(); // (6)
- ' $ 6 $
$ 6 $ Map.Entry &
$ 2 & !
I"
Review Questions
2 + - Map @
contains(Object o)
addAll(Collection c)
remove(Object o)
values()
toArray()
3 + @
$ values() Set
B $keySet()
Map 2 Collection
. $
. Map $
+ @
import java.util.*;
public class Lists {
public static void main(String[] args) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add(1, "3");
List list2 = new LinkedList(list);
list.addAll(list2);
list2 = list.subList(2, 5);
list2.clear();
System.out.println(list);
}
}
[1, 3, 2]
[1, 3, 3, 2]
[1, 3, 2, 1, 3, 2]
[3, 1, 2]
[3, 1, 1, 2]
+ comparator() @
ArrayList
HashMap
TreeSet
HashSet
TreeMap
+ $ java.util.Map.Entry@
Object getKey()
void remove()
Object getValue()
# $ equals() hashCode()
# compareTo() Comparable $
< - equals() #
$ hashCode() & $ HashSet
$ HashMap # Comparable
113 ) -
-
. 2 & .
!:5<" %
$ ( $
& $ + $
&
$
$
# $ - & $ equals()
Object - $#
- 6 $
$( /4 5 1
+ downloads $ !
?"&
versions $
$ latest - $ inShops
- $ older& !A"
&!>"&!
I"& !
K"
false - $ -
$ - & - $
latest - $ inShops
5 equals() $ SimpleVNO
- $& & , $ $ - &
& - , SimpleVNO -
& equals() $ false& -
$ - . $ 62 11I&
(9.1.1) versions $ $
versions $ List !
1;"
& $ vnoList&
contains() !1?" $ contains()
List equals() $ &
2 &false
!
33"
!34"& $ SimpleVNO compareTo()
Comparable & & -
! , 11A& ;?3" # 2 &
2 SimpleVNO - 8 &
-
+ test() 62 11I
$( 0 1 #6 equals()
import java.util.*;
// An array of downloads.
Integer[] downloads = { // (5)
new Integer(245), new Integer(786),
new Integer(54), new Integer(1010),
new Integer(123)};
// Various tests.
System.out.println("Test object reference and value equality:");
System.out.println(" latest: " + latest + ", inShops: " + inShops
+ ", older: " + older);
System.out.println(" latest == inShops: " +
(latest == inShops)); // (6)
System.out.println(" latest.equals(inShops): " +
(latest.equals(inShops))); // (7)
System.out.println(" latest == older: " +
(latest == older)); // (8)
System.out.println(" latest.equals(older): " +
(latest.equals(older))); // (9)
System.out.print("Array: ");
for (int i = 0; i < versions.length; i++) // (11)
System.out.print(versions[i] + " ");
boolean found = false;
for (int i = 0; i < versions.length && !found; i++)
found = searchKey.equals(versions[i]); // (12)
System.out.println("\n Search key found in array: "
+ found); // (13)
System.out.println("Sorted list:\n\t"
+ (new TreeSet(vnoList))); // (22)
System.out.println("Sorted map:\n\t"
+ (new TreeMap(versionStatistics))); // (23)
< %
. equals() $ %
%0 $ self&self.equals(self) $ true
equals() #
'
Reflexivity
$ - & # $
$% - - -
$! %
=="
if (this == argumentObj)
return true;
Symmetry
2 x.equals(y) equals() - $
x& 2 y.equals(x) equals() - $
y
# equals() & $
- # &$ $ equals()
&
. $ ! * "
equals() $
Transitivity
. $ $ equals()
equals() & equals()
$ %
$ * equals() &
equals() *
8 & 2
$ equals()
# equals() - &
$ $ $ # equals()
- & $ $
# & equals()
- equals() # &
equals() $ $ $
equals() equals() # $
equals() *
-
Consistency
- ! * " ! * "
$ 0 - &
! " 8 & - &
$ equals()
- & $
null comparison
- null equals()
false 2 7 .
$ $ $&
2 $ null %
if (argumentObj == null)
return false;
& $
$( 2 equals()
$ Object
& %
B &
$ B &
$ - $ B -
MyRefType equals() &
%
Reflexivity test
$ equals() &
true equals() 62 11K !
3"
equals() 62 11K $ - !
4"&
instanceof %
!
4" null 2 $ 2 (obj.getClass() !=
this.getClass()) -
- # & -
Argument casting
$ instanceof
$ & 62 11K !;"
* %
Field comparisons
6 -
0 $ &
# UsableVNO 62 11K $
$ : $ UsableVNO
- %
0 & - $ 0
2 & UsableVNO productInfo& &
%
(vno.productInfo == this.productInfo ||
(this.productInfo != null && this.productInfo.equals(vno.productInfo)))
2 vno.productInfo == this.productInfo $
- - $ productInfo #
NullPointerException & equals()
this.productInfo null
62 * $ &
! Float.floatToIntBits()
Double.doubleToLongBits()" *
5.5 ) ! equals() Float
Double "
< $ &
- & &
$ B
& equals() &
0 $ $
* # 2 & &
& & return
!
?" 62 11K
. & equals()
$( 3 #6 equals()
< %
- $ $< -
$ & $ equals()
8 & & 0
HashMap& equals() hashCode()
0 & compareTo
()
$ .
$& $ <
$ 2 B
$ 2 $ $ 2 $
, %
# $ &
5 ( $
$ # * %
8 $
# $ &
&
$
$ 0 &
$ *
& & % $
$ $
. $
.
, $
0 $& 2
. & $ $
$ $ $&
# - * java.util
! 113" &
Object %
hashCode() -
equals() - $
. & equals()
hashCode() B $
UsableVNO 62 11K 6 $ 62 111=
%
. $!
K11" %
hashCode() %
" % hashCode() -
$ 2 &
- $ equals()
2
$
% # %# -
equals() & hashCode()
- equals()
% # %# -
equals() & hashCode()
- # $ hashCode()
-
5 $ - 5
- &
-
# 62 1111& hashCode()
ReliableVNO $
%
$ ! , D 4& ?KA" 6
< $ equals()
- equals() &
hashCode()
$( hashCode()
B sfVal sf $ %
0 sf boolean% sfVal = sf ? 0 : 1
0 sf - $ $& hashCode()
$ equals() $%
0 sf $B $
0 2
$
0 equals() 2 7 &
hashCode() equals() . equals()
& ! & "
. $
2
. -
0 $&
-
hashCode() String $
41& &
0 2 & "abc"
%
$( #6 hashCode()
< %
...
Map: {(10.23.78)=1010, (2.48.28)=54, (3.49.1)=245, (8.19.81)=786, (9.1.1)=123}
Hash code for keys in the map:
(3.49.1): 332104
(8.19.81): 336059
(2.48.28): 331139
(10.23.78): 338102
(9.1.1): 336382
Search key (9.1.1) has hash code: 336382
Map contains search key: true
Exception in thread "main" java.lang.ClassCastException
...
int compareTo(Object o)
& - & #
ClassCastException
$ -
. compareTo() -
%
0 $ - & -
- & -
- & $
. ! "
compareTo() 0 2 & obj1.compareTo(obj2) > 0
obj2.compareTo(obj3) > 0& obj1.compareTo(obj3) > 0
*) $ 7
compareTo()
equals() & -
$ compareTo() equals()
. compareTo() -
# compareTo() equals()
# & $ equals() $
compareTo() & equals() compareTo()
$
. compareTo()
62 1114 0
& final 2
$( compareTo() Comparable
compareTo() $
ClassCastException& null NullPointerException
!
I" 62 1114
#
& & $
& 5 2
$ $ $
# $ * #
& ) compareTo
() !
K" !
13" 62 1114
B ) 0 2 &
!
K" 62 1114%
$ &
%
int $
, *boolean $
< > 0 - &
compareTo()
System.out.println("Sorted list:\n\t"
+ (new TreeSet(vnoList))); // (22)
System.out.println("Sorted map:\n\t"
+ (new TreeMap(versionStatistics))); // (23)
$( ' compareTo()
< %
...
Sorted list:
[(2.48.28), (3.49.1), (8.19.81), (9.1.1), (10.23.78)]
Sorted map:
{(2.48.28)=54, (3.49.1)=245, (8.19.81)=786, (9.1.1)=123, (10.23.78)=1010}
...
+ ' $ $
Collections Arrays java.util , 11I
!
1;" 62 111;&
$ vnoList%
2 %
. $ 2 !
K11"
&
$ searchKey 62 111;%
62 2 $ %
* $
# &L
$ # &
# $ $ &
Collections *
. $ $ ) & & *
$
# & $ ) &
$ ) %
$ Collections *
$ $ %
$ $ &
UnsupportedOperationException # & $
# & $
Sorting Collections
Collections
$
! , 11A"
Searching in Collections
Collections
$ 2 obj
&
2 %
*
$
)
$ & $
B $ $
NoSuchElementException
Singleton Collections
. & ! & $
$& $" $ $
Collections & $%
0 2 & $ %
$ & $ & $ $ %
Collections.EMPTY_SET
Collections.EMPTY_LIST
Collections.EMPTY_MAP
B n -
( '
- * $
- ) KKnull %
Integer $ *
2 & $%
Collections.sort(intList, Collections.reverseOrder());
Arrays.sort(strArray, Collections.reverseOrder());
( $ & &
( $ .
, i j
$ & &
5
. !
1"& jiveArray List& & & Set . !
3"
toArray() $ $
$uniqueJiveArray
Abstract Implementations
java.util
! 0 113 114" 0 2 & HashSet
AbstractSet & & &2 AbstractCollection
abstract $ $ $
& 2 )
Review Questions
- # equalsImpl()
equals()
return false;
return a == o.a;
. + * @
ArrayList
HashSet
Vector
TreeSet
LinkedList
/ + hashCode()
@
import java.util.*;
public class Measurement {
int count;
int accumulated;
public Measurement() {}
public void record(int v) {
count++;
accumulated += v;
}
public int average() {
return accumulated/count;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof Measurement))
return false;
Measurement o = (Measurement) other;
if (count != 0 && o.count != 0)
return average() == o.average();
return count == o.count;
}
public int hashCode() {
// ... PROVIDE IMPLEMENTATION HERE ...
}
}
return 31337;
return ~accumulated;
Chapter Summary
java.util %
$ $ Collection
& $ $ Set $
HashSet LinkedHashSet
& $ $ List
$ArrayList&Vector& LinkedList
& $ $ Map
$HashMap&LinkedHashMap& Hashtable
Comparator Comparable
& $ $
SortedSet SortedMap $TreeSet TreeMap
) $ ) $
$ Collections Arrays
Programming Exercises
+
# 2 $
, &
& $
& $ '
+ ! &
"(
( %