You are on page 1of 89

SEMINAR K THUT PHN MM

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

1-1. Nguyn tc hot ng


Mt chng trnh vit bng ngn ng lp trnh Java s c bin dch ra m ca my o java (m java bytecode). Sau my o Java chu trch nhim chuyn m java bytecode thnh m my tng ng.

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.

1-2. Java SE, JRE


Java SE (Java Platform, Standard Edition): cho php xy dng v trin khai cc ng dng trn desktop v server, cng nh thit b nhng v mi trng thi gian thc. JRE (Java Runtime environment): bao gm my o Java, cc th vin v cc tp tin cn thit. L mi trng thc thi mt ng dng Java.

1-3. Java ME, MIDP


Java ME (Java Platform, Micro Edition): platform pht trin cc ng dng trn thit b di ng.

MIDP (Mobile Information Device Profile): l mi trng thc thi ng dng Java trn thit b di ng.

2-1. JDK Compile v Run


Bc 1: Download JDK

Bc 2: Ci t JDK

2-1. JDK Compile v Run


Bc 3: Cu hnh my (Win 7)
- Click phi vo Computer - Properties - Advanced system settings - Chn th Advanced - Environment Variables

2-1. JDK Compile v Run


Bc 3: (tip) phn user variables nu: + Tn ti variable PATH: chn PATH v nhn Edit > ti value thm vo (ng dn n th mc bin ni ci JDK) + Cha tn ti variable PATH: nhn New > thm variable name PATH v value C:\Program Files\Java\jdk1.6.0_24\bin
;C:\Program Files\Java\jdk1.6.0_24\bin

2-1. JDK Compile v Run


Bc 4: M Notepad v to file HelloWorld.java ti C:\ vi ni dung:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }

2-1. JDK Compile v Run


Bc 5: Bin dch HelloWorld.java thnh HelloWorld.class (dng lnh javac) Start > Run > cmd > cd\ > javac HelloWorld.java

2-1. JDK Compile v Run


Bc 6: Chy (dng lnh java) java HelloWorld > xem kt qu

2-2. Eclipse Compile v Run


Bc 1: Download Eclipse

2. Eclipse Compile v Run


Bc 2: Gii nn tp tin va ti Bc 3: To project Hello World - Chy eclipse.exe - File > New > Java Project

- Tai Project name in Hello World

2-2. Eclipse Compile v Run


Bc 4: Thm class HelloWorld - Click phi vo Project Hello World > New > Class

2-2. Eclipse Compile v Run


Bc 4: (tip) - t tn class l HelloWorld - Check vo public static void main (String[] args) - Click Finish

2-2. Eclipse Compile v Run


Bc 5: Thm vo hm main on code System.out.println("Hello World"); Bc 6: Run v xem kt qu

2-3. Nhn xt
- JDK: + To mt file text + Dng javac bin dch file text thnh file .class + Dng java thc thi file .class

- Eclipse: mi thao tc thun li hn khi s dng giao din tng tc

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 { // . }

Khi mun s dng lp xemay vo chng trnh ta s khai bo nh sau:


import phuongtiengiaothong.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

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

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

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

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

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

52

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

53

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

54

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

55

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

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 + " " ); }
}
57

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

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 (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.
61

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

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.
65

Giao tip Set


Set k tha t Collection, h tr cc thao tc x l trn collection kiu tp hp Set khng c thm phng thc ring ngoi cc phng thc k tha t Collection. Giao Tip Set nh ngha b Collection khng c phn t trng lp

66

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.

67

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

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

Giao tip Map


Giao tip Map cung cp cc thao tc x l trn cc bng nh x. nh ngha collection c cc cp
kha - gi tr.

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

71

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.

72

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.

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

// 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); } } }
84

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

You might also like