You are on page 1of 62

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

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

S dng Linked List


public class ListTest { public static void main( String args[] ) { LinkedList list = new LinkedList(); list.insertAtFront( 5 ); list.insertAtFront( 7 ); list.insertAtBack( 9 ); list.insertAtBack( 8 ); list.insertAtBack( 4 ); list.print(); list.removeFromFront(); list.removeFromBack(); list.print();

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(); }

public void enqueue( int value ) { queueList.insertAtBack( value ); }


public int dequeue() { return queueList.removeFromFront(); } public boolean isEmpty() { return queueList.isEmpty(); } public void print() { queueList.print(); }

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

Binary Search Tree


Cy nh phn l cy m mi node khng c qu 2 node con. Cy tm kim nh phn l cy nh phn m:
Gi tr cc nt thuc cy con bn tri nh hn gi tr ca nt cha. Gi tr cc nt thuc cy con bn phi ln hn gi tr ca nt cha.

Duyt cy nh phn
Inorder traversal Preorder traversal Postorder traversal
24

Binary Search Tree


V d v Binary Search Tree

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

Ci t Binary Search Tree


public class TreeNode { int data; TreeNode leftNode, rightNode; public TreeNode( int nodeData ) { data = nodeData; leftNode = rightNode = null; } public void insert( int value ) { if ( value < data ) { if (leftNode == null) leftNode = new TreeNode(value); else leftNode.insert( value ); } else if ( value > data ) { if ( rightNode == null ) rightNode = new TreeNode(value); else rightNode.insert( value ); } } 26

Ci t Binary Search Tree


public class Tree { private TreeNode root; public Tree() { root = null; } public void insertNode( int insertValue ) { if ( root == null ) root = new TreeNode( insertValue ); else root.insert( insertValue ); } public void preorderTraversal() { preorder( root ); }

27

Ci t Binary Search Tree


public void inorderTraversal() { inorder( root ); } public void postorderTraversal() { postorder( root ); } private void preorder( TreeNode node ) { if ( node == null ) return; System.out.print( node.data + " " ); preorder( node.leftNode ); preorder( node.rightNode ); }
28

Ci t Binary Search Tree


private void inorder( TreeNode node ) { if ( node == null ) return; inorder( node.leftNode ); System.out.print( node.data + " " ); inorder( node.rightNode ); }

private void postorder( TreeNode node ) { if ( node == null ) return; postorder( node.leftNode ); postorder( node.rightNode ); System.out.print( node.data + " " ); }
29

S dng Binary Search Tree


public class TreeTest { public static void main( String[] args ) { Tree tree = new Tree(); int value; for ( int i = 1; i <= 10; i++ ) { value = ( int ) ( Math.random() * 100 ); tree.insertNode( value ); } System.out.println ( "\n\nPreorder traversal" ); tree.preorderTraversal(); System.out.println ( "\n\nInorder traversal" ); tree.inorderTraversal(); System.out.println ( "\n\nPostorder traversal" ); tree.postorderTraversal();
30

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 (t Java 1.2)


L mt kin trc hp nht biu din v thao tc trn cc collection. Gip cho vic x l cc collection c lp vi biu din chi tit bn trong ca chng.
33

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

Giao tip Collection


Cung cp cc thao tc chnh trn collection nh thm/xo/tm phn t... V d:
boolean add(Object element); boolean remove(Object element); boolean contains(Object element); int size(); boolean isEmpty();

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

Giao tip List


List k tha t Collection, n cung cp thm cc phng thc x l collection kiu danh sch (Danh sch l mt collection vi cc phn t c xp theo ch s). Mt s phng thc ca List
Object get(int index); Object set(int index, Object o); void add(int index, Object o); Object remove(int index); int indexOf(Object o); int lastIndexOf(Object o);
38

Giao tip Set


Set k tha t Collection, h tr cc thao tc x l trn collection kiu tp hp (Mt tp hp yu cu cc phn t phi khng c trng lp). Set khng c thm phng thc ring ngoi cc phng thc k tha t Collection.

39

Giao tip SortedSet


SortedSet k tha t Set, n h tr thao tc trn tp hp cc phn t c th so snh c. Cc i tng a vo trong mt SortedSet phi ci t giao tip Comparable hoc lp ci t SortedSet phi nhn mt Comparator trn kiu ca i tng . Mt s phng thc ca SortedSet:
Object first(); // ly phn t u tin (nh nht) Object last(); // ly phn t cui cng (ln nht) SortedSet subSet(Object e1, Object e2); // ly mt tp cc phn t nm trong khong t e1 ti e2.
40

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:

Iterator it = c.iterator(); while ( it.hasNext() ) { Point p = (Point) it.next(); System.out.println( p.toString() ); }


42

Giao tip Map


Giao tip Map cung cp cc thao tc x l trn cc bng nh x (Bng nh x lu cc phn t theo kho v khng c c 2 kho trng nhau). Mt s phng thc ca Map
Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); ...
43

Giao tip Map


Map cung cp 3 cch view d liu:
View cc kho:
Set keySet(); // Tr v cc kho

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

Sau khi nhn c kt qu l mt collection, ta c th dng iterator duyt cc phn t ca n.


44

Giao tip SortedMap


Giao tip SortedMap k tha t Map, n cung cp thao tc trn cc bng nh x vi kho c th so snh c. Ging nh SortedSet, cc i tng kho a vo trong SortedMap phi ci t giao tip Comparable hoc lp ci t SortedMap phi nhn mt Comparator trn i tng kho.

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"));

// look up a value System.out.println(phoneDir.get("5581814"));


// iterate through all entries Set entries = phoneDir.entrySet(); Iterator iter = entries.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println("key=" + key + ", value=" + value); }

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

You might also like