Professional Documents
Culture Documents
1
Collections
3
Linked List
• Linked list là cấu trúc gồm các node liên kết
với nhau thông qua các mối liên kết. Node
cuối linked list được đặt là null để đánh dấu
kết thúc danh sách.
• Linked list giúp tiết kiệm bộ nhớ so với mảng
trong các bài toán xử lý danh sách.
• Khi chèn/xoá một node trên linked list, không
phải dãn/dồn các phần tử như trên mảng.
• Việc truy nhập trên linked list luôn phải tuần
tự.
4
Linked List
15 10
5
Linked List
firstNode lastNode
H D ... Q
6
Cài đặ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;
}
public LinkedList()
{
firstNode = lastNode = null;
}
11
Mô tả insertAtFront
(a ) firstNode
7 11
new ListNode
12
(b ) firstNode
7 11
new ListNode
12
12
Mô tả insertAtBack
12 7 11 5
12 7 11 5
13
Mô tả removeFromFront
(a ) firstNode lastNode
12 7 11 5
(b ) firstNode lastNode
12 7 11 5
removeItem
14
Mô tả removeFromBack
(a ) firstNode lastNode
12 7 11 5
12 7 11 5
removeItem
15
Sử dụng 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
17
Cài đặt Stack
public class Stack
{
private LinkedList stackList;
public Stack()
{
stackList = new LinkedList();
}
public void push( int value )
{
stackList.insertAtFront( value );
}
18
Sử dụng 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
20
Cài đặ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ử dụng 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à một cấu trúc phi tuyến (non-linear).
• Mỗi node trên cây có thể có nhiều liên kết tới
node khác.
Nút gốc
Nút trong
Nút lá
23
Binary Search Tree
• Cây nhị phân là cây mà mỗi node không có
quá 2 node con.
• Cây tìm kiếm nhị phân là cây nhị phân mà:
• Giá trị các nút thuộc cây con bên trái nhỏ hơn giá
trị của nút cha.
• Giá trị các nút thuộc cây con bên phải lớn hơn giá
trị của nút cha.
• Duyệt cây nhị phân
• Inorder traversal
• Preorder traversal
• Postorder traversal
24
Binary Search Tree
47
11 43 65 93
7 17 31 44 68
25
Cài đặ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
}
Cài đặ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
Cài đặ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
Cài đặ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ử dụng 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 );
}
31
Collection
• Collection là đối tượng có khả năng chứa
các đối tượng khác.
• Các thao tác thông thường trên
collection
• Thêm/Xoá đối tượng vào/khỏi collection
• Kiểm tra một đối tượng có ở trong collection
không
• Lấy một đối tượng từ collection
• Duyệt các đối tượng trong collection
• Xoá toàn bộ collection
32
Collections Framework
33
Collections Framework
34
Collections Framework
35
Interfaces
<<interface>> <<interface>>
Collection Map
<<interface>>
SortedSet
36
Giao tiếp Collection
• Cung cấp các thao tác chính trên collection
như thêm/xoá/tìm phần tử... Ví dụ:
• boolean add(Object element);
• boolean remove(Object element);
• boolean contains(Object element);
• int size();
• boolean isEmpty();
• Nếu lớp cài đặt Collection không muốn hỗ
trợ các thao tác làm thay đổi collection như
add, remove, clear... nó có thể tung ra
ngoại lệ UnsupportedOperationException.
37
Giao tiếp List
38
Giao tiếp Set
39
Giao tiếp SortedSet
40
Duyệt collection
41
Duyệt collection
42
Giao tiếp Map
43
Giao tiếp Map
• Map cung cấp 3 cách view dữ liệu:
• View các khoá:
Set keySet(); // Trả về các khoá
• View các giá trị:
Collection values(); // Trả về các giá trị
• View các cặp khoá-giá trị
Set entrySet(); // Trả về các cặp khoá-giá trị
• Sau khi nhận được kết quả là một
collection, ta có thể dùng iterator để
duyệt các phần tử của nó.
44
Giao tiếp SortedMap
• Giao tiếp SortedMap kế thừa từ Map, nó
cung cấp thao tác trên các bảng ánh xạ với
khoá có thể so sánh được.
• Giống như SortedSet, các đối tượng khoá
đưa vào trong SortedMap phải cài đặt giao
tiếp Comparable hoặc lớp cài đặt SortedMap
phải nhận một Comparator trên đối tượng
khoá.
45
Implementations
• Các cài đặt trong Collections Framework
chính là các lớp collection có sẵn trong Java.
Chúng cài đặt các collection interface ở trên
để thể hiện các cấu trúc dữ liệu cụ thể. Ví
dụ: mảng động, danh sách liên kết, cây đỏ
đen, bảng băm...
46
Implementations
LinkedList
List
ArrayList
HashSet
Set LinkedHashSet
SortedSet TreeSet
HashMap
Map LinkedHashMap
SortedMap TreeMap
47
Mô tả các cài đặt
48
Mô tả các cài đặt
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
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"));
// 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"));
56
Các lớp bao
57
Algorithms
58
Ví dụ: Trộn bài
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));
Collections.shuffle(numbers);
System.out.println("After shuffling:" + numbers + "\n");
}
}
59
Collections Framework
• Legacy Implementations
• Là các lớp cũ được cài đặt bổ sung thêm các
collection interface.
• Vector: Có thể thay bằng ArrayList
• Hastable: Có thể thay bằng HashMap
• Abstract Implementations
• Là các lớp trừu tượng đã cài đặt các collection
interface mà ta có thể kế thừa để tạo ra các
collection mới.
• AbstractCollection, AbstractSet,
AbstractList...
60
Bài tập
61
Bài tập