Professional Documents
Culture Documents
Bi 8. Collections
Cu trc d liu trong Java
Linked List Stack v Queue Tree
Collections Framework
Danh sch (List) Tp hp (Set) Bng nh x (Map)
Bi tp
2
Cu trc d liu
Cu trc d liu l cch t chc d liu gii quyt vn . Mt s cu trc d liu ph bin:
Mng (Array) Danh sch lin kt (Linked List) Ngn xp (Stack) Hng i (Queue) Cy (Tree)
Linked List
Linked list l cu trc gm cc node lin kt vi nhau thng qua cc mi lin kt. Node cui linked list c t l null nh du kt thc danh sch. Linked list gip tit kim b nh so vi mng trong cc bi ton x l danh sch. Khi chn/xo mt node trn linked list, khng phi dn/dn cc phn t nh trn mng. Vic truy nhp trn linked list lun phi tun t.
4
Linked List
Th hin Node thng qua lp t tham chiu (self-referential class)
class Node { private int data; private Node nextNode; // constructors and methods ... }
1 5
1 0
5
Linked List
Mt linked list c qun l bi tham chiu ti node u v node cui.
f s o ir tN de la tN e s od
.. .
Ci t Linked List
// Dinh nghia mot node trong linked list class ListNode { int data; ListNode nextNode; ListNode(int value) { this(value, null); } ListNode(int value, ListNode node) { data = value; nextNode = node; } int getData() { return data; } ListNode getNext() { return nextNode; }
7
Ci t Linked List
// Dinh nghia lop LinkedList public class LinkedList { private ListNode firstNode; private ListNode lastNode; public LinkedList() { firstNode = lastNode = null; } public void insertAtFront(int insertItem) { if ( isEmpty() ) firstNode = lastNode = new ListNode( insertItem ); else firstNode = new ListNode( insertItem, firstNode ); }
8
Ci t Linked List
public void insertAtBack( int insertItem ) { if ( isEmpty() ) firstNode = lastNode = new ListNode( insertItem ); else lastNode = lastNode.nextNode = new ListNode( insertItem ); }
public int removeFromFront() { int removeItem = -1; if ( ! isEmpty() ) { removeItem = firstNode.data; if ( firstNode == lastNode ) firstNode = lastNode = null; else firstNode = firstNode.nextNode; } return removeItem; }
Ci t Linked List
public int removeFromBack() { int removeItem = -1; if ( ! isEmpty() ) { removeItem = lastNode.data; if ( firstNode == lastNode ) firstNode = lastNode = null; else { ListNode current = firstNode; while ( current.nextNode != lastNode ) current = current.nextNode; lastNode = current; current.nextNode = null; } } return removeItem; }
10
Ci t Linked List
public boolean isEmpty() { return (firstNode == null); } public void print() { ListNode node = firstNode; while (node != null) { System.out.print(node.data + " "); node = node.nextNode; } System.out.println("\n"); }
11
M t insertAtFront
(a)
fi st d r No e 7 n L st d ew i No e 12 11
(b)
fi st d r No e 7 n L st d ew i No e 12 11
12
M t insertAtBack
(a)
fi st d r No e
la tN e ne L tN de s od w is o
1 2
(b)
1 1
fi st d r No e
la tN e ne L tN de s od w is o
1 2
1 1
13
M t removeFromFront
(a)
f st od ir N e
l st d a No e
1 2
(b)
11
5 l st d a No e
f st od ir N e
1 2 re v te mo eI m
11
14
M t removeFromBack
(a)
fi st d r No e
la tN e s od
12
(b)
7 cu re r nt
1 1
5 la tN e s od
fi st d r No e
12
1 1
r o I m em ve te
15
16
Stack
Stack l mt cu trc theo kiu LIFO (Last In First Out), phn t vo sau cng s c ly ra trc. Hai thao tc c bn trn Stack
Chn phn t: Lun chn vo nh Stack (push) Ly ra phn t: Lun ly ra t nh Stack (pop)
17
Ci t Stack
public class Stack { private LinkedList stackList; public Stack() { stackList = new LinkedList(); } public void push( int value ) { stackList.insertAtFront( value ); }
public int pop() { return stackList.removeFromFront(); } public boolean isEmpty() { return stackList.isEmpty(); } public void print() { stackList.print(); }
18
S dng Stack
public class StackTest { public static void main(String[] args) { Stack stack = new Stack(); stack.push(5); stack.push(7); stack.push(4); stack.push(8); stack.print(); stack.pop(); stack.pop(); }
stack.print();
19
Queue
Queue (Hng i) l cu trc theo kiu FIFO (First In First Out), phn t vo trc s c ly ra trc. Hai thao tc c bn trn hng i
Chn phn t: Lun chn vo cui hng i (enqueue) Ly ra phn t: Ly ra t u hng i (dequeue)
20
Ci t Queue
public class Queue { private LinkedList queueList; public Queue() { queueList = new LinkedList(); }
21
S dng Queue
public class QueueTest { public static void main(String[] args) { Queue queue = new Queue(); queue.enqueue(5); queue.enqueue(7); queue.enqueue(4); queue.enqueue(8); queue.print(); queue.dequeue(); queue.dequeue(); queue.print();
22
Tree
Tree l mt cu trc phi tuyn (non-linear). Mi node trn cy c th c nhiu lin kt ti node khc.
Nt gc
Nt trong
Nt l
23
Duyt cy nh phn
Inorder traversal Preorder traversal Postorder traversal
24
4 7
Cy con tri Cy con phi
2 5 1 1 7 1 7 4 3 3 4 1 4 6 5 6 8
7 7 9 3
25
27
private void postorder( TreeNode node ) { if ( node == null ) return; postorder( node.leftNode ); postorder( node.rightNode ); System.out.print( node.data + " " ); }
29
Bi tp ti lp
Bi 1: Dng Stack vit chng trnh in ra dng nh phn ca mt s nguyn dng cho trc. Bi 2: Ci t phng thc search trong lp Tree tm mt phn t c gi tr cho trc.
31
Collection
Collection l i tng c kh nng cha cc i tng khc. Cc thao tc thng thng trn collection
Thm/Xo i tng vo/khi collection Kim tra mt i tng c trong collection khng Ly mt i tng t collection Duyt cc i tng trong collection Xo ton b collection
32
Collections Framework
Cc collection u tin ca Java:
Mng Vector: Mng ng Hastable: Bng bm
Collections Framework
Mt s li ch ca Collections Framework
Gim thi gian lp trnh Tng cng hiu nng chng trnh D m rng cc collection mi Khuyn khch vic s dng li m chng trnh
34
Collections Framework
Collections Framework bao gm
Interfaces: L cc giao tip th hin tnh cht ca cc kiu collection khc nhau nh List, Set, Map. Implementations: L cc lp collection c sn c ci t cc collection interfaces. Algorithms: L cc phng thc tnh x l trn collection, v d: sp xp danh sch, tm phn t ln nht...
35
Interfaces
<<interface>> Collection <<interface>> Map
<<interface>> Set
<<interface>> List
<<interface>> SortedMap
<<interface>> SortedSet
36
Nu lp ci t Collection khng mun h tr cc thao tc lm thay i collection nh add, remove, clear... n c th tung ra ngoi l UnsupportedOperationException.
37
39
Duyt collection
Cc phn t trong collection c th c duyt thng qua Iterator. Cc lp ci t Collection cung cp phng thc tr v iterator trn cc phn t ca chng.
Collection c;
Iterator it = c.iterator();
...
41
Duyt collection
Iterator cho php duyt tun t mt collection. Cc phng thc ca Iterator:
boolean hasNext(); Object next(); void remove();
V d:
View cc gi tr:
Collection values(); // Tr v cc gi tr
View cc cp kho-gi tr
Set entrySet(); // Tr v cc cp kho-gi tr
45
Implementations
Cc ci t trong Collections Framework chnh l cc lp collection c sn trong Java. Chng ci t cc collection interface trn th hin cc cu trc d liu c th. V d: mng ng, danh sch lin kt, cy en, bng bm...
46
Implementations
List
LinkedList ArrayList HashSet Set LinkedHashSet SortedSet HashMap Map LinkedHashMap SortedMap TreeMap
47
TreeSet
M t cc ci t
ArrayList: Mng ng, nu cc phn t thm vo vt qu kch c mng, mng s t ng tng kch c. LinkedList: Danh sch lin kt 2 chiu. H tr thao tc trn u v cui danh sch. HashSet: Bng bm. LinkedHashSet: Bng bm kt hp vi linked list nhm m bo th t cc phn t. TreeSet: Cy en (red-black tree).
48
M t cc ci t
HashMap: Bng bm (ci t ca Map). LinkedHashMap: Bng bm kt hp vi linked list nhm m bo th t cc phn t (ci t ca Map). TreeMap: Cy en (ci t ca Map).
49
V d 1: TreeSet
// This program sorts a set of names import java.util.*; public class TreeSetTest1 { public static void main(String[] args) { SortedSet names = new TreeSet(); names.add(new String("Minh Tuan")); names.add(new String("Hai Nam")); names.add(new String("Anh Ngoc")); names.add(new String("Trung Kien")); names.add(new String("Quynh Chi")); names.add(new String("Thu Hang")); System.out.println(names); } }
50
V d 2: Student Set
class Student implements Comparable { private String code; private double score; public Student(String code, double score) { this.code = code; this.score = score; } public double getScore() { return score; } public String toString() { return "(" + code + "," + score + ")"; }
51
V d 2: Student Set
public boolean equals(Object other) { Student otherStu = (Student) other; return code.equals(otherStu.code); } public int compareTo(Object other) { Student otherStu = (Student) other; return code.compareTo(otherStu.code); }
52
V d 2: Student Set
// This programs sorts a set of students by name and then by score import java.util.*; public class TreeSetTest2 { public static void main(String[] args) { SortedSet stu = new TreeSet(); stu.add(new Student("A05726", 8.5)); stu.add(new Student("A06338", 7.0)); stu.add(new Student("A05379", 7.5)); stu.add(new Student("A06178", 9.5)); System.out.println(stu); SortedSet sortByScore = new TreeSet(new Comparator() // create an inner class
53
V d 2: Student Set
{ public int compare(Object a, Object b) { Student itemA = (Student) a; Student itemB = (Student) b; double scoreA = itemA.getScore(); double scoreB = itemB.getScore(); if ( scoreA < scoreB ) return -1; else return 1; } }); // end of inner class
sortByScore.addAll(stu); System.out.println(sortByScore);
54
V d 3: HashMap
// This program stores a phone directory by hashing import java.util.*;
public class MyMapTest { public static void main(String[] args) { Map phoneDir = new HashMap(); phoneDir.put("5581814", new String("Dept. Informatics")); phoneDir.put("8584490", new String("Defense Staff")); phoneDir.put("8587346", new String("Administrative Staff")); phoneDir.put("7290028", new String("Student Club"));
// print all entries System.out.println(phoneDir); // remove an entry phoneDir.remove("8584490");
55
V d 3: HashMap
// replace an entry phoneDir.put("7290028", new String("International Relation"));
56
Cc lp bao
Collection ch lm vic trn cc Object. Nhng kiu d liu c bn nh: byte, short, int, long, double, float, char, boolean khng th a c trc tip vo Collection m phi thng qua cc lp bao. Cc lp bao: Byte, Short, Int, Long, Double, Float, Char, Boolean. V d:
Integer intObject = new Integer(9); int value = intObject.intValue();
57
Algorithms
Cc thut ton c ci t nh nhng phng thc tnh ca lp Collections Mt s phng thc ca Collections:
static Object max(Collection c) static Object min(Collection c) static int binarySearch(List list, Object key) static void sort(List list) static void shuffle(List list) cc phng thc to synchronized collection cc phng thc to read-only collection
58
V d: Trn bi
import java.util.*;
public class MyShuffleTest { public static void main(String[] args) { List numbers = new ArrayList(52); for (int i = 1; i <= 52; i++) numbers.add(new Integer(i)); System.out.println("Before shuffling:" + numbers + "\n"); Collections.shuffle(numbers); System.out.println("After shuffling:" + numbers + "\n");
59
Collections Framework
Legacy Implementations
L cc lp c c ci t b sung thm cc collection interface. Vector: C th thay bng ArrayList Hastable: C th thay bng HashMap
Abstract Implementations
L cc lp tru tng ci t cc collection interface m ta c th k tha to ra cc collection mi. AbstractCollection, AbstractSet, AbstractList...
60
Bi tp
1. Ci t cc x l Exception cn thit cho cc phng thc trong LinkedList, Stack, Queue, Tree. 2. Vit chng trnh cho php nhp mt xu k t t bn phm, sau hin th xu ny theo th t ngc li (dng Stack). 3. Vit chng trnh cho php nhp mt danh sch sinh vin sau sp xp danh sch theo th t tng dn. Dng ArrayList v Collections.sort().
61
Bi tp
4. Vit chng trnh h tr tra cu t in n gin. Chng trnh lu cc t v ngha ca t trong mt Collection hoc mt Map. 5. M rng bi tp trn bng cch dng file lu tr cc t. 6. Ci t li Queue t lp ArrayList. 7. Gii cc bi ton ng dng trong mn Cu trc d liu bng cch s dng Collections Framework.
62