Java Object Oriented Programming 09
-
Upload
futaro-kun -
Category
Documents
-
view
89 -
download
0
description
Transcript of Java Object Oriented Programming 09
-
Kiu d liu Collections
Bi 9 - Kiu d liu Collection
-
2
Ni dung
Kiu Collections
Giao din
Thc thi
Cc thut ton
Lp vt cha Set v Map
Bi 9 - Kiu d liu Collection
-
3
Kiu Collections
Mt collection, hay cn gi l container, l mt i tng dng nhm
nhiu phn t trong mt n v duy nht.
Cc collection c s dng lu tr, truy xut v thao tc d liu.
V d: mt tp hp cc qun bi, cc th mc th, mt danh b in
thoi,
http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
Bi 9 - Kiu d liu Collection
-
4
Collection framework
Mt collection framework l mt kin trc thng nht
biu din v thao tc vi cc d liu kiu collection.
Ba thnh phn ca mt collection framework:
Giao din: cc kiu d liu tru tng dng biu
din cc collection.
Thc thi: cc thc thi c th ca cc giao din ca collection.
Thut ton: Cc phng thc h tr nh sp xp, tm
kim, cc i tng thc thi cc giao din ca collection.
Bi 9 - Kiu d liu Collection
-
5
Java collection framework
Lm gim cng vic lp trnh,
Tng tc v cht lng chng trnh,
Cho php kh nng tng tc gia cc API khng lin quan,
Lm gim cng sc tm hiu v s dng cc API mi,
Lm gim vic thit k cc API mi,
Thc y ti s dng phn mm.
Bi 9 - Kiu d liu Collection
-
6
Ni dung
Kiu Collections
Giao din
Thc thi
Cc thut ton
Lp vt cha Set v Map
Bi 9 - Kiu d liu Collection
-
7
Giao din
Cc giao din li ca collection ng gi nhiu kiu khc nhau ca collection.
Cc giao din ny cho php cc collection c thao tc mt cch c lp
vi cc thc thi ca chng.
Collection
Set List
SortedSet
Queue
Map
SortedMap
Bi 9 - Kiu d liu Collection
-
8
Giao din
Tt c cc giao din ca Java collection framework l:
public interface Collection
Chng ta nn xc nh kiu E ca cc i tng cha trong collection.
E c th l mt trong cc kiu i tng:
Integer, Double, String
Object
Bi 9 - Kiu d liu Collection
-
9
Duyt collection
Hai cch duyt qua collection:
Bng cu trc foreach
Bng cc i tng Iterator
Cu trc foreach
for (Object o : collection)
do something
Cc i tng Iterator
Collection c;
Iterator iter = c.iterator();
while (iter.hasNext()) { E e = iter.next(); ...}
Bi 9 - Kiu d liu Collection
-
10
Ni dung
Kiu Collections
Giao din
Thc thi
Cc thut ton
Lp vt cha Set v Map
Bi 9 - Kiu d liu Collection
-
11
Thc thi
Cc thc thi thng dng ca collection
HashSet, TreeSet
ArrayList, LinkedList
PriorityQueue
HashMap, TreeMap
Bn nn c ti liu v cc lp ny trong API Documentation ny bit
y cc chc nng ca chng.
Packages: java.util.*
Bi 9 - Kiu d liu Collection
-
12
V d: List
// create a list of odd numbers
List odds = new ArrayList();
for (int i = 1; i < 50; i = i + 2) {
odds.add(i);
}
// print the list: first way
for (Integer i : odds) {
System.out.println(i);
}
// print the list: second way
Iterator iter = odds.iterator();
int i;
while (iter.hasNext()) {
i = iter.next();
System.out.println(i);
}
// print the list: third way
for (int j = 0; j < odds.size(); j++) {
i = odds.get(j);
System.out.println(i);
}
Bi 9 - Kiu d liu Collection
-
13
Ni dung
Kiu Collections
Giao din
Thc thi
Cc thut ton
Lp vt cha Set v Map
Bi 9 - Kiu d liu Collection
-
14
Cc thut ton
Cc thut ton a hnh trong Collection framework ca Java c
th ti s dng.
Tt c cc thut ton u c vit di dng phng thc
tnh.
i s u tin lun l Collection hot ng.
Nhiu thut ton lm vic trn danh sch.
Bi 9 - Kiu d liu Collection
-
15
Cc thut ton
Cc thut ton gm:
Sp xp
Xo trn
X l d liu thng xuyn
Tm kim
Hp nht
Vic tm kim cc gi tr cc i
Bi 9 - Kiu d liu Collection
-
16
Sp xp
Cc thut ton sp xp sp xp li danh sch cc phn t ca n tng dn theo mt quan h th t no .
Cc th t t nhin:
Xu k t
S
K t
Ngy thng
i tng ?
Bi 9 - Kiu d liu Collection
-
17
Sp xp
Giao din Comparable quy nh quan h th t cho mt lp.
Cc i tng ca mt lp c th c sp xp t ng nu
lp thc thi giao din Comparable.
Cc lp quan trng ca Java platform m thc thi giao din
Comparable bao gm:
Boolean, Byte, Character, Short, Integer, Long, Float, Double,
BigInteger, BigDouble.
String, Data, File, CollationKey
Bi 9 - Kiu d liu Collection
-
18
Sp xp
Nu ta c gng sp xp mt danh sch m cc phn t ca n
khng thc thi Comparable, phng thc sp xp s nm mt
i tng thuc lp ClassCastException.
Giao din Comparable:
public interface Comparable {
public int compareTo(T o);
}
Tr li mt gi tr ln hn, nh hn hay bng 0 ty thuc i tng ang xt ln hn, nh hn hay bng
vi i tng c so snh.
Bi 9 - Kiu d liu Collection
-
19
Sp xp
Example: Name.java, NameSort.java
public class NameSort { public static void main(String[] args) {
Name nameArray[] = {
new Name("John", "Smith"),
new Name("Karl", "Ng"),
new Name("Jeff", "Smith"),
new Name("Tom", "Rich")
};
List names = Arrays.asList(nameArray);
Collections.sort(names);
System.out.println(names);
}
}
Bi 9 - Kiu d liu Collection
-
20
Sp xp
Nu cc i tng m chng ta cn phi sp xp khng thc thi
Comparable, chng ta c th quy nh mt Comparator c dng
sp xp.
Giao din Comparator:
public interface Comparator {
int compare(T o1, T o2);
}
Bi 9 - Kiu d liu Collection
-
21
Sp xp
Gi s ta c mt lp Employee nh sau:
public class Employee implements
public Name name() { ...
public int number() { ...
public Date hireDate() { ...
...
}
Bi 9 - Kiu d liu Collection
-
22
Sp xp
ng nhin, chng ti c th sp xp danh sch cc nhn vin theo tn ca h.
Nu cn chng ta cng c th sp xp danh sch ny theo th
t v thm nin?
Bi 9 - Kiu d liu Collection
-
23
Sp xp
public class EmpSort {
static final Comparator SENIORITY_ORDER =
new Comparator() {
public int compare(Employee e1, Employee e2) {
int dateCmp = e2.hireDate().compareTo(e1.hireDate());
if (dateCmp != 0)
return dateCmp;
return (e1.number() < e2.number() ? -1 :
(e1.number() == e2.number() ? 0 : 1));
}
};
// Employee database
static final Collection employees = ... ;
public static void main(String[] args) {
List e = new ArrayList(employees);
Collections.sort(e, SENIORITY_ORDER);
System.out.println(e);
}
}
Ta so snh cc gi tr numbers khi m hai gi
tr ngy thng bng nhau
Bi 9 - Kiu d liu Collection
-
24
Xo trn
Thut ton xo trn l ngc li ca thut ton sp xp
Sp xp li mt danh sch da trn u vo t mt ngun ngu
nhin m tt c cc hon v c th xy ra vi kh nng ngang nhau.
Rt hu ch trong vic thc hin cc tr chi may ri (th, xc sc
...)
Bi 9 - Kiu d liu Collection
-
25
Xo trn
public class Shuffle {
public static void main(String[] args) {
List list = new ArrayList();
for (String a : args)
list.add(a);
Collections.shuffle(list, new Random());
System.out.println(list);
}
}
public class Shuffle {
public static void main(String[] args){
List list = Arrays.asList(args);
Collections.shuffle(list);
System.out.println(list);
}
}
Dng mt ngun ngu
nhin mc nh.
Bi 9 - Kiu d liu Collection
-
26
Thao tc d liu
Collection cung cp 5 thut ton thc hin cc thao tc d
liu trn cc i tng ca lp List:
reverse
fill
copy
swap
addAll
Bi 9 - Kiu d liu Collection
-
27
Tm kim
Thut ton binarySearch tm kim mt phn t trong
mt danh sch c sp xp.
Nu phn t c tm thy, ch s ca n c tr li, nu khng mt gi tr ch s m c tr li.
Hai dng ca thut ton:
Cho mt danh sch v mt phn t tm kim;
Cho mt danh sch, mt phn t tm kim v mt
Comparator.
Bi 9 - Kiu d liu Collection
-
28
Hp nht
Thut ton v tn sut:
m s ln xut hin ca mt phn t trong mt collection.
Thut ton xc nh tp ri nhau
Xc nh xem hai collection cc tch ri nhau khng.
Bi 9 - Kiu d liu Collection
-
29
Tm cc i
Gi tr cc i:
min ca mt collection
max ca mt collection
Hai dng:
Cho mt Collection
Cho mt Collection v mt Comparator
c cc ti liu JDK API xem cc thut ton v cc v d c th.
Bi 9 - Kiu d liu Collection
-
30
Example: Sort an Array
String[] fruits = new String[] {"Pineapple","Apple",
"Orange", "Banana"};
Arrays.sort(fruits);
int i=0;
for(String temp: fruits){
System.out.println("fruits " + ++i + " : " + temp);
}
Bi 9 - Kiu d liu Collection
-
31
Example: Sort an ArrayList
List fruits = new ArrayList();
fruits.add("Pineapple");
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
Collections.sort(fruits);
int i=0;
for(String temp: fruits){
System.out.println("fruits " + ++i + " : " + temp);
}
Bi 9 - Kiu d liu Collection
-
32
Sort an Object with Comparable
public class Fruit{
private String fruitName;
private int quantity;
public Fruit(String fruitName, int quantity) {
this.fruitName = fruitName;
this.quantity = quantity;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
} Bi 9 - Kiu d liu Collection
-
33
Sort an Object with Comparable
public class SortFruitObject{
static void showList(Fruit[] fruits){
int i=0;
for(Fruit temp: fruits){
System.out.println("fruits " + ++i + " : " + temp.getFruitName()
+ ", Quantity : " + temp.getQuantity());
}
}
public static void main(String args[]){
Fruit[] fruits = new Fruit[4];
Fruit pineappale = new Fruit("Pineapple",70);
Fruit apple = new Fruit("Apple",100);
Fruit orange = new Fruit("Orange",80);
fruits[0]=pineappale;
fruits[1]=apple;
fruits[2]=orange;
Arrays.sort(fruits);
showList(fruits);
}
}
}
Fruit cannot be cast to
java.lang.Comparable
Bi 9 - Kiu d liu Collection
-
34
Sort an Object with Comparable
public class Fruit implements Comparable {
private String fruitName;
private int quantity;
public Fruit(String fruitName, int quantity) {
public String getFruitName() {
public void setFruitName(String fruitName) {
public int getQuantity() {
public void setQuantity(int quantity) {
//override the compareTo() method
public int compareTo(Fruit compareFruit) {
int compareQuantity = ((Fruit) compareFruit).getQuantity();
return this.quantity - compareQuantity;
}
}
Bi 9 - Kiu d liu Collection
-
35
Sort an Object with Comparator
public class Fruit implements Comparable {
private String fruitName;
private int quantity;
public Fruit(String fruitName, int quantity) {
public String getFruitName() {
public void setFruitName(String fruitName) {
public int getQuantity() {
public void setQuantity(int quantity) {
public int compareTo(Fruit compareFruit) {
public static Comparator FruitNameComparator
= new Comparator() {
public int compare(Fruit fruit1, Fruit fruit2) {
String fruitName1 = fruit1.getFruitName().toUpperCase();
String fruitName2 = fruit2.getFruitName().toUpperCase();
return fruitName1.compareTo(fruitName2);
}
};
} Bi 9 - Kiu d liu Collection
-
36
Sort an Object with Comparator
public class SortFruitObject{
static void showList(Fruit[] fruits){
int i=0;
for(Fruit temp: fruits){
System.out.println("fruits " + ++i + " : " + temp.getFruitName()
+ ", Quantity : " + temp.getQuantity());
}
}
public static void main(String args[]){
Fruit[] fruits = new Fruit[4];
Fruit pineappale = new Fruit("Pineapple",70);
Fruit apple = new Fruit("Apple",100);
Fruit orange = new Fruit("Orange",80);
fruits[0]=pineappale;
fruits[1]=apple;
fruits[2]=orange;
Arrays.sort(fruits);
showList(fruits);
Arrays.sort(fruits, Fruit.FruitNameComparator);
showList(fruits;)
}
}
fruits 1 : Apple, Quantity : 100
fruits 2 : Orange, Quantity : 80
fruits 3 : Pineapple, Quantity : 70
fruits 1 : Pineapple, Quantity : 70
fruits 2 : Orange, Quantity : 80
fruits 3 : Apple, Quantity : 100
Bi 9 - Kiu d liu Collection
-
37
Ni dung
Kiu Collections
Giao din
Thc thi
Cc thut ton
Lp vt cha Set v Map
Bi 9 - Kiu d liu Collection
-
38
Tm cc ch trong vn bn
Cc ch (token, word) l mt dy k t lin nhau, ngn cch bi k t
trng.
V d:
Dng Tom likes Jerry gm 3 ch: Tom, likes, Jerry.
Dng Hc sinh hc sinh hc gm 5 ch:
C 3 ch khc nhau l Hc, sinh, hc.
Nu khng phn bit hoa thng th ch c 2 ch khc nhau.
Bi 9 - Kiu d liu Collection
-
39
Tm cc ch trong vn bn
Cho trc mt tp vn bn ting Anh hoc ting Vit, ta xt hai bi ton sau:
Lit k cc ch khc nhau trong vn bn
m tn s cc ch khc nhau trong vn bn
Bi 9 - Kiu d liu Collection
-
40
Tm cc ch trong vn bn
gii bi ton 1, ta dng kiu vt cha tp hp:
Giao din Set
Ci t ca Set l HashSet
gii bi ton 2, ta dng kiu vt cha nh x:
Giao din Map
Ci t ca Map l HashMap
Bi 9 - Kiu d liu Collection
-
41
Cc giao din trong th vin
Th vin cc lp vt cha c nhiu giao din cho php thao tc vi nhiu
kiu d liu thng dng:
Set, Map, List, Queue
Collection
Set List
SortedSet
Queue
Map
SortedMap
Bi 9 - Kiu d liu Collection
-
42
Reader reader = null;
BufferedReader bufferedReader = null; try { // open a reader using UTF-8 encoding so that we can
// read Vietnamese text reader = new InputStreamReader(new FileInputStream(fileName), "UTF-8"); bufferedReader = new BufferedReader(reader);
c tp vn bn
S dng bng m UTF-8
c tp
Bi 9 - Kiu d liu Collection
-
43
String line = null; // read the input file, line by line while ((line = bufferedReader.readLine()) != null) { // split the line into tokens String[] tokens = line.split(Constants.DELIMITERS); // add tokens to the set for (String token : tokens) { tokenSet.add(token);
}
}
public static final String DELIMITERS = "[\\s,\\.\\(\\)]+";
c tp vn bn
Biu thc chnh quy ch nh cc k t
trng, du phy, du chm, m ngoc,
ng ngoc
Bi 9 - Kiu d liu Collection
-
44
Nu thay HashSet bng TreeSet th ta c tp c sp xp theo th t t nhin ca phn t
Cc phn t l String s c sp theo th t t in
private Set tokenSet;
tokenSet = new HashSet();
public void print() {
System.out.println("There are " + tokenSet.size() + " different tokens."); for (String token : tokenSet) {
System.out.println(token);
}
}
S dng Set
Bi 9 - Kiu d liu Collection
-
45
Mi nh x c cp phn t: Key Value Trong bi ton 2, Key l token, Value l mt s nguyn m s ln token xut hin Key, Value u phi l cc kiu i tng (khng th l kiu d liu c s)
Key = String
Value = Integer
private Map tokenCounter;
tokenCounter = new HashMap();
S dng Map
Bi 9 - Kiu d liu Collection
-
46
// add tokens to the counter
for (String token : tokens) { Integer count = tokenCounter.get(token); if (count != null) { tokenCounter.put(token, count + 1); } else { tokenCounter.put(token, 1);
}
}
S dng phng thc get(Key) ly Value gn vi Key.
Nu khng c Key th hm get tr v null
Java 5+ t ng chuyn i gia i v new Integer(i) vi i l mt s nguyn
S dng Map
Bi 9 - Kiu d liu Collection
-
47
/**
* Prints the token counter to the standard console. */ public void print() { System.out.println("There are " + tokenCounter.keySet().size() + " different tokens."); for (String token : tokenCounter.keySet()) { System.out.println(token + " --> " + tokenCounter.get(token)); } }
Nu thay HashMap bng TreeMap th tp kha c sp xp theo th t t nhin.
S dng Map
Bi 9 - Kiu d liu Collection