Professional Documents
Culture Documents
Mt s vn c bn v JAVA
Nhm 07 : Nguyn Hng Phng Phm Thin Phc Nguyn Gip Nguyn Sinh
Ni dung trnh by
1. Nguyn tc hot ng ca Java. Khi nim Java platform: + Java SE: JRE + Java ME: MIDP 2. Cng c mi trng pht trin (JDK, Eclipse). 3. C php Java (package, tn file, tn lp, cch tha k lp v thc thi giao din) 4. Cc loi Interfaces v lp mng Java
Java l mt ngn ng lp trnh va bin dch va thng dch. Chng trnh ngun vit bng ngn ng lp trnh Java c ui *.java u tin c bin dch thnh tp tin c ui *.class v sau s c trnh thng dch thng dch thnh m my.
MIDP (Mobile Information Device Profile): l mi trng thc thi ng dng Java trn thit b di ng.
Bc 2: Ci t JDK
2-3. Nhn xt
- JDK: + To mt file text + Dng javac bin dch file text thnh file .class + Dng java thc thi file .class
3-1. Package
- Vic ng gi cc lp li to thnh mt th vin dng chung gi l package. - Mt package c th cha mt hay nhiu lp bn trong, ng thi cng c th cha mt package khc bn trong.
3-1. Package
- khai bo mt lp thuc mt gi no y ta phi dng t kha package. -Dng khai bo gi phi l dng u tin trong tp tin khai bo lp. - Cc tp tin khai bo lp trong cng mt gi phi c lu trong cng mt th mc.
3-1. Package
V d:
package phuongtiengiaothong; class xemay { // . }
3-2. Tn file, tn lp
- Tn lp: + Bao gm mt chui cc k t (Unicode), k s (Unicode), k s. + Phi bt u bng mt ch ci, du gch di _ hay du dollar '$' + Khng c trng vi cc t kha + Khng c khong trng gia - Tn file: file .java phi c tn trng vi tn lp
3-3. K tha
Mt lp con (subclass) c th k tha tt c nhng vng d liu v phng thc ca mt lp khc (siu lp - superclass). Nh vy vic to mt lp mi t mt lp bit sao cho cc thnh phn (fields v methods) ca lp c cng s thnh cc thnh phn (fields v methods) ca lp mi. Khi ta gi lp mi l lp dn xut (derived class) t lp c (superclass). C th lp c cng l lp c dn xut t mt lp no , nhng i vi lp mi va to th lp c l mt lp siu lp trc tip (immediate supperclass).
3-3. K tha
Dng t kha extends ch lp dn xut.
class A extends B
{ // }
3-4. Interface
Khi nim: Nh chng ta bit mt lp trong java ch c mt siu lp trc tip hay mt cha duy nht (n tha k). trnh i tnh phc tp ca a tha k (multi-inheritance) trong lp trnh hng i tng, Java thay th bng giao tip (interface). Mt lp c th c nhiu giao tip (interface) vi cc lp khc tha hng thm vng d liu v phng thc ca cc giao tip ny.
3-4. Interface
Khai bo: Interface c khai bo nh mt lp. Nhng cc thuc tnh ca interface l cc hng (khai bo dng t kha final) v cc phng thc ca giao tip l tru tng (mc d khng c t kha abstract). Trong cc lp c ci t cc interface ta phi tin hnh ci t c th cc phng thc ny.
3-4. Interface
V d:
public interface sanpham { static final String nhasx = Honda VN; static final String dienthoai = 08-8123456; public int gia(String s_model); }
//khai bo 1 lp c ci t interface public class xemay implements sanpham { // ci t li phng thc ca giao din trong lp public int gia(String s_model) { if (s_model.equals(2005)) return (2000); else return (1500); } public String chobietnhasx() { return (nhasx); } }
3-4. Interface
C mt vn khc vi lp l mt giao din (interface) khng ch c mt giao din cha trc tip m c th dn xut cng lc nhiu giao din khc (hay c nhiu giao din cha). Khi n s k tha tt c cc gi tr hng v cc phng thc ca cc giao din cha. Cc giao din cha c lit k thnh chui v cch nhau bi du phy ,. Khai bo nh sau:
public interface InterfaceName extends interface1, interface2, interface3 { // }
4. Interfaces
http://download.oracle.com/javase/tutorial/collecti ons/interfaces/
Lp trnh Java c bn
29
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)
30
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)
31
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.
32
Linked List
Th hin Node thng qua lp t tham chiu (selfreferential class)
class Node { private int data; private Node nextNode; // constructors and methods ... }
1 5
1 0
33
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
.. .
34
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; } }
35
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 ); }
36
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; }
37
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; }
38
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"); } }
39
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
40
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
41
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
42
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
43
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)
45
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(); }
}
46
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();
} }
47
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)
48
Ci t Queue
public class Queue { private LinkedList queueList; public Queue() { queueList = new LinkedList(); }
49
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(); } }
50
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
51
Duyt cy nh phn
Inorder traversal Preorder traversal Postorder traversal
52
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
53
54
55
private void postorder( TreeNode node ) { if ( node == null ) return; postorder( node.leftNode ); postorder( node.rightNode ); System.out.print( node.data + " " ); }
}
57
Collections Framework
Collections Framework bao gm nhiu lp v giao din trong khung cng tc. Khung cng tc ca cc Collection Java da trn trin khai thc hin c th mt s giao din nh ngha cc kiu su tp (collection)
59
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
60
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
62
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...
63
Interfaces
<<interface>> Collection <<interface>> Map
<<interface>> Set
<<interface>> List
<<interface>> SortedMap
<<interface>> SortedSet
64
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.
65
66
67
68
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();
...
69
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() ); }
70
71
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
72
73
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...
74
Implementations
List
LinkedList ArrayList HashSet Set LinkedHashSet SortedSet HashMap Map LinkedHashMap SortedMap TreeMap
75
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).
76
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).
77
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); } }
78
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 + ")"; }
79
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); } }
80
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
81
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); } }
82
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");
83
V d 3: HashMap
// replace an entry phoneDir.put("7290028", new String("International Relation"));
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();
85
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
86
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"); } }
87
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...
88
Collections Framework
89