Truyen2U.Top - Tên miền mới của Truyen2U.Net. Hãy sử dụng ứng dụng 1.1.1.1 để đọc truyện nhé!

ontapjav

Ôn tập Java
1.    Hướng đối tượng trong Java. Ý nghĩa của từ khóa: public, protected, private,

static, final, abstract, synchronized, this, super…
(Tham khảo thêm slide Aptech TV – session 3)
    Hướng đối tượng trong Java:

- Hướng đối tượng trong Java tương tự như C++ nhưng Java là một ngôn ngữ lập trình

hướng đối tượng hoàn toàn, không thể viết một ứng dụng hướng thủ tục trong Java
- Tất cả mọi thứ đề cập đến trong Java đều liên quan đến các đối tượng được định nghĩa

trước, thậm chí hàm chính (hàm main) của một chương trình viết bằng Java cũng phải đặt

bên trong một lớp
- Hướng đối tượng trong Java không có tính đa kế thừa (multi inheritance) như trong

C++ mà thay vào đó Java đưa ra khái niệm interface để hỗ trợ tính đa kế thừa.

    Ý nghĩa của từ khóa public, protected, private, static, final, abstract,

synchronized, this, super

Kiểm soát truy xuất vào các thành phần của lớp và đối tượng

 

- public: tạo ra mức độ truy xuất lớn nhất, chỉ ra rằng methods hay properties có thể

được gọi bởi bất kỳ đồi tượng nào
- protected: Sử dụng protected để cho phép các thành phần của
class được truy nhập bởi các subclass trong bất kỳ package nào,
hoặc các class trong cùng package.
- private: Sử dụng private để ẩn hoàn toàn các thành phần của lớp (dữ liệu, phương

thức), chúng sẽ không thể được truy nhập từ bên ngoài lớp.
- 2 từ khóa trên chỉ có thể sử dụng cho các thành phần của class,
không thể sử dụng cho class ngoài cùng.
- no modifier: Sử dụng default modifier (no modifier) thì các
thành phần của class được truy nhập từ bất kỳ lớp nào trong
cùng package, nhưng không thể từ package khác.
- public: Sử dụng public cho phép các thành phần của class có
thể được truy nhập từ bất kỳ lớp nào.
- public và default modifier có thể được sử dụng cho các thành
phần của class, cũng như sử dụng cho chính class
- static: dữ liệu static chứa giá trị trong vùng nhớ chung, không thể dùng cho lớp ngoài

cùng.
Lưu ý:
• Thông thường để an toàn cho vùng dữ liệu của các đối tượng người ta tránh dùng tiền

tố public, mà thường chọn tiền tố private để ngăn cản quyền truy cập đến vùng dữ liệu

của một lớp từ các phương thức bên ngoài lớp đó.
- static: dung để định nghĩa một biến của một lớp. Đây có thể coi như là một biến toàn

cục vì dù lớp chứa biến static được khởi tạo bao nhiêu lần thì nó chỉ có duy nhất một biến

static (nằm ở cùng vùng nhớ). Biến static cũng được dung để khai báo một phương thức.

Một phương thức static chỉ có thể truy cập đến biến static của class mà thôi.
public class Math
{
       public static double s_pi = 3.14;
       public double m_pi = 3.14;
       public static double calculateCircle(double r)
       {
           return r*r*s_pi; //nếu dùng m_pi thì sẽ sai.
       }
}
public class MathExecute
{
       public static void main(String args[])
       {
            System.out.println("pi = " + Math.s_pi);//kết quả là pi = 3.14
            Math.s_pi = 3.1412;
            Math m = new Math();
            System.out.println("pi = " + m.s_pi);//kết quả là pi = 3.1412
            m.s_pi = 3.141;
            System.out.println("pi = " + Math.s_pi);//kết quả là pi = 3.141
       }
}

- extends( kế thừa): Một lớp A1 kế thừa lớp A nghĩa là lớp A1 chứa tất cả thuộc tính,

phương thức là protected hoặc public của A.
public class A {
public int a;
protected int b;
private int c;
/**
* constructor – Hàm khởi tạo - của lớp A.
*/
public A() {
a = 0;
b = 1;
c = 2;
}
public int getNextA() {
return a+1;
}
public int getNextB() {
return b+1;
}
public int getNextC() {
return c+1;
}
}
public class A1 extends A {
public void setA (int a) {
this.a = a;
}
public void setB (int b ){
this.b = b;
}
/**
* Hàm setC này sai (bị báo lỗi) vì không thể truy cập tới biến c.
*/
public void setC (int c) {
this.c = c;
}
/**
* hàm main sau sẽ in ra kết quả: a = 1; b = 2; c = 3;
*/
public static void main(String args[]) {
A1 a1 = new A1();
System.out.println("a = " + a1.getNextA()
+ "; b = " + a1.getNextB()
+ "; c = " + a1.getNextC() + ";");
}
}


- abstract:
Nếu lớp A là abstract thì lớp A không thể tự khởi tạo mà nó chỉ được dùng cho việc kế

thừa.
abstract class A
 {
private int a;
public A()
{
a = 100;
}
public int getA()
{
return a;
}
}

public class A1 extends A
{
public A1()
{
}
public static void main(String args[])
{
A a = new A(); //--> sai
A1 a1 = new A1();
System.out.println("a = " + a1.getA());//kết quả là: a = 100
}
}

Nếu phương thức setA của lớp A là abstract thì nó không được có phần thân hàm mà

phần thân hàm sẽ được viết trong lớp kế thừa A. Lớp A cũng phải là abstract.
abstract class A
{
protected int a;
public A()
{
a = 100;
}
public int getA()
{
return a;
}
/**
* Nếu phương thức setA có phần thân hàm sẽ bị báo lỗi.
*/
abstract void setA(int a);
}// ket thuc abstract class A

public class A1 extends A {
/**
* Nếu lớp A1 không có hàm setA thì sẽ bị báo lỗi.
*/
public void setA(int a) // phan than ham se se duoc viet tai day
 {
this.a = a;
}
public static void main(String args[]) {
A1 a1 = new A1();
a1.setA(1);
System.out.println("a = " + a1.getA());//kết quả là: a = 1
}
}

- final: Nếu lớp A là final thì lớp A sẽ ko được kế thừa bởi bất kỳ lớp nào.
final class A {
public a;
public A() {
}
//và các phương thức khác...
}
/**
* lớp A1 sau sẽ bị báo lỗi.
*/
public class A1 extends A {
}

Nếu phương thức getA là final thì phương thức này sẽ không thể bị override bởi các lớp

con.
public class A
{
public int a;
public A()
{
a = 100;
}
final int getA() {
return a;
}
}
public class A1 extends A {
/**
* vì không thể override hàm getA nên sự xuất hiện của hàm getA ở
* lớp A1 là sai --> bị báo lỗi.
*/
int getA() {
return a-1;
}
}

Nếu một biến a (thuộc lớp A) là final thì biến này là một hằng, và phải được khởi tạo

trong constructor hoặc lúc khai báo. Nếu gán giá trị cho a ngoài constructor hoặc ngoài

lúc khai báo thì sẽ bị báo lỗi.
public class A {
final int a; //có thể gán giá trị tại đây.
public A() {
//nếu lúc khai báo chưa gán giá trị
//mà lại không được khởi tạo trong constructor --> bị báo lỗi
a = 100;
}
/**
* nếu có thêm phương thức sau thì sẽ bị báo lỗi.
*/
public setA (int a) {
this.a = a; //sai
}
}

- Interface and implements:
Một lớp A là interface nghĩa là mọi phương thức, hàm đều không có phần thân hàm mà

chỉ là liệt kê những phương thức, hàm cho các lớp khác implements. Nếu lớp A1

implements interface A và không có đủ các phương thức, hàm được liệt kê trong A thì sẽ

bị báo lỗi.
interface A
{
    public int getNextA();
    public void setA(int a);
}
public class A1 implements A
{
    private int a = 0;
    public static void main(String args[])
    {
        A1 a = new A1();
        a.setA(10);
        System.out.println("a = " + a.getNextA());//k?t qu? là: a = 11
    }
/**
* N?u thi?u m?t trong 2 phuong th?c sau s? báo l?i.
*/
    public int getNextA()
    {
        return a+1;
    }
    public void setA(int a)
    {
        this.a = a;
    }
}

- synchronized: dùng để ngăn các tác động của các đối tượng khác lên đối tượng đang xét

trong khi đang đồng bộ hóa. Dùng trong lập trình miltithreads.
- Biến this là một biến ẩn tồn tại trong tất cả các lớp trong ngôn ngữ Java. Một class

trong Java luôn tồn tại một biến this.
- Biến this được sử dụng trong khi chạy và tham khảo đến bản thân lớp chứa nó.
Ví dụ:
<tiền tố> class A
{<tiền tố> int <field_1>;
<tiền tố> String <field_2>;
// Contructor của lớp A
public A(int par_1, String par_2)
{
this.field_1 = par_1; this.field_2 = par_2;
}
<tiền tố> <kiểu trả về> <method_1>()
{ // … }
<tiền tố> <kiểu trả về> <method_2>()
{
this.method_1()
// …
}
}
.
Dùng biến this để gọi một constructor khác:
class Foo
{
private int i;
public int getI()
{
return i;
}
public void setI(int i)
{
this.i = i;
}
public Foo()  {  this(0); }
public Foo(int x)  
{
this.i=x;    
}
}

- super: (Session 4 – slide 7 aptech tv)
 Tái sử dụng hàm tạo cũng như các phương thức đã được cài đặt ở lớp cơ sở từ lớp con
Để gọi lại hàm tạo của lớp cha trong hàm tạo của lớp con
public class Person {
protected String name;
/**
* Constructor for objects of class Person
*/
public Person(String name) {
// To do:
this.name=name;
}
public void count() {
System.out.println(“1 2 3");
}
}

public class Employee extends Person {
/**
* Constructor for objects of class
Employee
*/
public Employee(String name) {
// To do:
super(name);
}
public void count() {
super.count();
System.out.println("4 5 6");
}
}
public class Client {
public void test() {
Person jack=new Person("Jack");
Employee peter=new Employee("Peter");
jack.count();
peter.count();
}
}

Overriding là
public class Person {
protected String name;
/**
* Constructor for objects of class Person
*/
public Person(String name) {
// To do:
this.name=name;
}
public void sayHello() {
System.out.println("Hello!"+name);
}
}
public class Employee extends Person {
/**
* Constructor for objects of class
Employee
*/
public Employee(String name) {
// To do:
super(name);
}
public void sayHello() {
System.out.println("Hi!"+name);
}
}
public class Client {
public void test() {
Person jack=new Employee("Jack");
Employee peter=new Employee("Peter");
jack.sayHello();
peter.sayHello();
}
}

 THAM KHẢO THÊM LEC3 CÓ CÁC VD VỀ CÁC TỪ KHÓA RẤT CỤ THỂ
 SESSION 5: SLIDE APTECH TA



2.3. Ý nghĩa của xử lý ngoại lệ trong java. Cho ví dụ về try/ catch/ finally, throw, throws

• Khi một phương thức gặp lỗi nào đó, ví dụ như chia không, vượt kích thước mảng, mở

file chưa tồn tại… thì các ngoại lệ sẽ
được ném ra. Chương trình dừng lại ngay lập tức, toàn bộ phần mã phía sau sẽ không

được thực thi.
• Java hỗ trợ cách thức để xử lý ngoại lệ (exception handling) tuỳ theo nhu cầu của

chương trình.
 Xử lý exception:
• Khối try/catch
– Đặt đoạn mã có khả năng xảy ra ngoại lệ trong khối try
– Đặt đoạn mã xử lý ngoại lệ trong khối catch
– Khi xảy ra ngoại lệ trong khối try, các câu lệnh trong khối catch sẽ được thực hiện tuỳ

vào kiểu của ngoại lệ.
– Sau khi thực hiện xong khối catch, điều khiển
sẽ được trả lại cho chương trình.

try {
//Các câu lệnh có khả năng tung ra ngoại lệ
}catch(Exception ex) {
//Các câu lệnh xử lý trong tình huống bắt được exception
}finally
{
// câu lệnh tronq finally luôn được thực thi dù có hay ko có exception
}

Tung ra Exception sử dụng từ khóa throw:
 
Tung ra Exception sử dụng từ khóa throws:

 

import java.util.*;
import java.io.*;
public class exception
{
    public static void main(String args[])
    {
        int a=0;
        int b=1;
        int c;
        try
        {
            c = b/a;
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception");
        }
        finally
        {
            System.out.println("Still executed if(or if not) has

exception");
        }


    }
}


import java.util.*;
import java.io.*;
public class exception
{
    public static int getEndMember(int[] a) throws

ArrayIndexOutOfBoundsException
    { // phai co tu khoa static nhe
        return a[a.length]; // phai la lenqth -1 khi do chi co cac ptu tu a[0] 

a[2] (3-1)
    }
    public static void main(String[] args)
    {
        int[] a = {1, 2, 3};
        try
        {
            getEndMember(a);
// Đoạn code trên sẽ in ra ArrayIndexOutOfBoundsException bởi vì hàm getEndMember

đã truy xuất phần tử a[3] không có trong mảng.
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            

System.out.println("ArrayIndexOutOfBoundsException");
        }
    }
}


Chúng ta cũng có thể dùng throw để quăng ra một exception Object
import java.util.*;
import java.io.*;
public class exception
{

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int a;
        int b;
        int c;
        System.out.println("enter value for a,b,c");
        System.out.print("a= ");
        a = sc.nextInt();
        System.out.print("b= ");
        b = sc.nextInt();
        try
        {
            c = b/a;
            if (a ==0)
            {
                throw new ArithmeticException();
            }
            else
            {
                System.out.println("c= "+c);
            }
        }
        catch(ArithmeticException e)
        {
            System.out.println("ArithmeticException");
        }
    }
}



4. Phân biệt cấu trúc LIST, SET, MAP. Cho vd tổng hợp về sử dụng cấu trúc này.

- List:
+ List interface kế thừa Collection interface
+ A list is an ordered collection of elements. The user can have control of the order in

which a given element has to be inserted.
+ A user can access a particular element or search for elements in the list.
+ List allow duplication of elements and also null elements. Some of the methods

supported by the List interface are listed:
•    indexOf(Object o): tra ve the index >=0 hoac -1 neu ko co element tronq List
•    subList(int fromIndex, int toIndex)
•    lastIndexOf(Object o):
•    get(int index)

- Set: the Set interface contains methods inherited from

•    Collection interface with the restriction(hạn chế) that duplicate elements are

prohibited(bị cấm)
•    Design for finding value quickly

- Comparison of Set with List:
Set: ko duplicate.
List: cho duplicate

- Map:
•    The map interface allows storage of elements in pairs, termed “key” and

“values”, where each key maps to one value.
•    For a better understanding, lists which have numeric keys can be considered

as Map objects. However, there is no direct connection between a List and Map except

that they are both defined in java.util package. The Map interface does not extent the

Collection interface
•    Maps have their own hierarchy, for maintaining  the key-value

associations(hiệp hội). The interface describes a mapping from keys to values, without

duplicate keys
•    Some of methods supported by this interface are listed:
o    hashCode(): returns hashCode value for this map
o    values(): returns the values contained in the map
o    size(): returns the number of key – value mappings in this map


 

import java.util.*;
import java.io.*;
class testList
{
    public static void main(String args[])
    {

        // vd ve List
        ArrayList<String> a = new ArrayList();
        a.add("HiepTM");
        a.add("DucTM");
        a.add("HiepTM");// Day la diem khac biet cua List va Set: co the

co element nhu nhau(HiepTM)
        for(String s:a)
        {
            System.out.println(s+"\t");// in ra HiepTm DucTM
        }
        System.out.println("===============================");
        // vd ve Set: HashSet
        Set set = new HashSet();
        set.add("HiepTM");
        set.add("DucTM");
        set.add("HiepTM");// khi cho 2 elements nhu nhau thi khi in chi

coi nhu la 1 element
        System.out.println(set);
        System.out.println("================================");
        // vd ve Set: TreeSet --> elements duoc sap xep
        Set set1 = new TreeSet();
        set1.add("HiepTM");
        set1.add("DucTM");
        set1.add("HiepTM");
        set1.add("TuTM");
        System.out.println(set1);
        System.out.println("================================");
        // vd ve Map
        Map<Integer, String> map = new HashMap();
        map.put(3,"HiepTM");
        map.put(1,"DucTM");
        map.put(2,"TuTM");
        System.out.println(map);
    }
}

5. YN của nghĩa của cấu trúc dữ liệu tổng quát. Cho VD cụ thể sử dụng TreeMap
-  YN:
•    Giảm thời gian lập trình
•    Tăng cường hiệu năng chương trình
•    Dễ mở rộng các collection mới
•    Khuyến khích việc sử dụng lại mã chương trình
- Cho vd:
VD1 :
import java.util.*;
import java.io.*;
class testList
{
    public static void main(String args[])
    {        
        // vd ve Map: TreeMap
        Map<Integer, String> sortedMap = new TreeMap();
        sortedMap.put(2,"B");
        sortedMap.put(3,"A");
        sortedMap.put(1,"C");
        System.out.println(sortedMap);
    }
}

VD2:
import java.util.*;

public class TreeMapExample
{
    public static void main(String[] args)
    {
        System.out.println("Tree Map Example!\

");
        TreeMap <Integer, String>tMap = new TreeMap<Integer,

String>();
        //them du lieu vao tree map
        tMap.put(1, "Sunday");
        tMap.put(2, "Monday");
        tMap.put(3, "Tuesday");
        tMap.put(4, "Wednesday");
        tMap.put(5, "Thursday");
        tMap.put(6, "Friday");
        tMap.put(7, "Saturday");
        //lay tat ca cac khoa
        System.out.println("Keys of tree map: " + tMap.keySet());
        //lay tat ca cac qia tri
        System.out.println("Values of tree map: " + tMap.values());
        //Lay qia tri dua vao khoa voi so khoa la 5
        System.out.println("Key: 5 value: " + tMap.get(5)+ "\

");
        //Lay khoa va qia tri cua phan tu dau tien
        System.out.println("First key: " + tMap.firstKey() + " Value: " +

tMap.get(tMap.firstKey()) + "\

");
        //Lay khoa va qia tri cua phan tu cuoi
        System.out.println("Last key: " + tMap.lastKey() + " Value: " +

tMap.get(tMap.lastKey()) + "\

");
        //Xoa khoa va qia tri cua phan tu dau
        System.out.println("Removing first data: " +

tMap.remove(tMap.firstKey()));
        System.out.println("Now the tree map Keys: " + tMap.keySet());
        System.out.println("Now the tree map contain: " + tMap.values()

+ "\

");
        //Xóa khóa và giá tr? c?a ph?n t? d?u
        System.out.println("Removing last data: " +

tMap.remove(tMap.lastKey()));
        System.out.println("Now the tree map Keys: " + tMap.keySet());
        System.out.println("Now the tree map contain: " + tMap.values());
    }
}

6. So sánh LinkedList và ArrayList. Cho VD
ArrayList    LinkedList
- Biểu diễn một list như là một Dynamic Array
- Array được resize khi mà full
- Truy cập đến các phần tử nqẫu nhiên(random)
- Implements tất cả methods of List<E>
- Thêm và bớt các e yêu cầu dịch chuyển các e tiếp theo(xq)
- Cần phải được resized khi hết space    - Biểu diễn một list nhu là một doubly-linked

list with a header node
- Implements all methods of list
- Thêm và bớt các e được thực hiện = cách tổ chức lại các kết nối links – ko cần dịch

chuyển
-  Các node được phân bổ và phát hành khi cần thiết


 



 

    ArrayList    LinkedList
Add(i,obj) and Remove(i)    O(n)    O(n)

Contains(obj)    O(n)    O(n)
Add(obj)    O(1)    O(1)
Add(0,obj)    O(n)    O(1)
Get(i) and set(i,obj)    O(1)    O(ns)


VD:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;



/**
 *
 * @author TranMinhHiep
 *
 */
public class IteratorArrayList {

    public static void main(String[] args)
    {
        List<String> words = new ArrayList<String>();
        words.add("AAA1");
        words.add("AAA2");
        words.add("AAA3");

        for (String w: words)
        {
            System.out.println(w);
        }
        words.remove(0);
        Iterator <String> iter=words.iterator();
        while (iter.hasNext())
        {
            System.out.println(iter.next());
        }
        
    }
}


import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


/**
 *
 * @author TranMinhHiep
 */
public class ListArrayList {
public static void main (String[] args){
    // List Example implement with ArrayList
                            //ArrayList<String>();
        List<String> ls=new LinkedList<String>();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");
        ls.remove(0);
        Iterator it=ls.iterator();

        while(it.hasNext())
        {
           String value=(String)it.next();
           System.out.println("Value :"+value);
        }
}
}









7. Phân biệt TreeMap và TreeSet. Cho VD

TreeSet    TreeMap<K,V>
- Stores its elements in a tree, and orders its elements based on their values
- Working with Comparable objects (or takes a comparator as a parameter)
- Implements a set as Binary Search Tree
- Containts, add, and remove methods run in O(log n ) time
- Iterator returns elements in ascending orders    - The TreeMap Class implements

the Map interface but stores elements in a tree. The TreeMap returns keys in sorted

order. If there  is no need to retrieve Map elements sorted by key, then the HashMap

would be a more practical structure to use
- Works with Comparable keys (or takes a comparator as parameter)
-  Implements a set as Binary Search Tree
- containsKey, get, and put methods run in 0(log n) time

VD TreeSet:
SortedSet interface: các elements sẽ được sx theo tanq dan
VD1:
import java.util.*;
public class TreeSetTest1
{
    public static void main(String args[])
    {
        SortedSet names = new TreeSet();
        names.add(new String("F"));
        names.add(new String("A"));
        names.add(new String("D"));
        names.add(new String("C"));
        names.add(new String("U"));
        System.out.println(names);

    }
}


VD2:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ddu.lec4.pTreeSet;

/**
 *
 * @author Tran Minh Hiep
 */

class Student implements Comparable<Student> // cai lại method compareTo
{
     private String code;
     private String name;
     private Integer score;

    public void setCode(String code) {
        this.code = code;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setScore(Integer score) {
        this.score = score;
    }
     


     public Student(String code, String name, Integer score)
     {
          this.code = code;
          this.score = score;
          this.name=name;
     }

     public Integer getScore()
     {
          return score;
     }
     public String getCode()
     {
          return code;
     }
    public String getName()
     {
          return name;
     }
    @Override
    public String toString()
    {
          return "(" + code + "," + score + ")";
    }
    @Override
     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);
//    }
    @Override
    public int compareTo(Student other)
    {

          return code.compareTo(other.code);
          
    }
}


package ddu.lec4.pTreeSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
/**
 *
 * @author Tran Minh Hiep
 */
public class TreeSet2
{
     public static void main(String[] args)
     {
         SortedSet<Student> stu = new TreeSet<Student>();
         stu.add(new Student("A05726","AA", 8));
         stu.add(new Student("A06338","AB", 7));
         stu.add(new Student("A05379", "AC",7));
         stu.add(new Student("A06178", "AD",9));

         Student st1=new Student("A06338","AD", 7);

         
      System.out.println(stu);

      boolean kt = stu.contains(st1);
      if (kt)
          System.out.println("found");
         SortedSet<Student> sortByScore = new TreeSet<Student>(new Comparator()
                 // create an inner class
             {@Override
                    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);
     }
}


VD về TreeMap

import java.util.*;

public class TreeMapExample
{
    public static void main(String[] args)
    {
        System.out.println("Tree Map Example!\

");
        TreeMap <Integer, String>tMap = new TreeMap<Integer,

String>();
        //them du lieu vao tree map
        tMap.put(1, "Sunday");
        tMap.put(2, "Monday");
        tMap.put(3, "Tuesday");
        tMap.put(4, "Wednesday");
        tMap.put(5, "Thursday");
        tMap.put(6, "Friday");
        tMap.put(7, "Saturday");
        //lay tat ca cac khoa
        System.out.println("Keys of tree map: " + tMap.keySet());
        //lay tat ca cac qia tri
        System.out.println("Values of tree map: " + tMap.values());
        //Lay qia tri dua vao khoa voi so khoa la 5
        System.out.println("Key: 5 value: " + tMap.get(5)+ "\

");
        //Lay khoa va qia tri cua phan tu dau tien
        System.out.println("First key: " + tMap.firstKey() + " Value: " +

tMap.get(tMap.firstKey()) + "\

");
        //Lay khoa va qia tri cua phan tu cuoi
        System.out.println("Last key: " + tMap.lastKey() + " Value: " +

tMap.get(tMap.lastKey()) + "\

");
        //Xoa khoa va qia tri cua phan tu dau
        System.out.println("Removing first data: " +

tMap.remove(tMap.firstKey()));
        System.out.println("Now the tree map Keys: " + tMap.keySet());
        System.out.println("Now the tree map contain: " + tMap.values()

+ "\

");
        //Xóa khóa và giá tr? c?a ph?n t? d?u
        System.out.println("Removing last data: " +

tMap.remove(tMap.lastKey()));
        System.out.println("Now the tree map Keys: " + tMap.keySet());
        System.out.println("Now the tree map contain: " + tMap.values());
    }
}

8. Hàng đợi ưu tiên Priority Queue. Cho VD
- Hàng đợi ưu tiên Priority Queue:

• In a priority queue, items are processed NOT in order of arrival, but in order of

priority.
• Trong một hàng đợi ưu tiên, các mục được xử lý Không theo thứ tự đến, nhưng theo

thứ tự ưu tiên.
• java.util:
– Queue interface
– PriorityQueue (implements Queue)
 

• The same methods as in Queue:  isEmpty, add(addLast), remove(removeFirst),

peek(getFirst).

• PriorityQueue<E> class
• Works with Comparable objects (or takes a comparator as a parameter).
• The smallest item has the highest priority.
• Implements a priority queue as a min-heap.
• Both add and remove methods run in O(log n) time; peek runs in O(1) time.

    Priority queues similar to queues but the elements are not arranged in FIFO

structure. They are arranged in a user-defined manner.
    The elements are ordered either by natural ordering or according to a

comparator.
    A priority queue is unbound and allows the queue to grow in capacity.
(Tai Lieu Aptech)

// StringLengthComparator.java
import java.util.*;
public class StringLengthComparator implements Comparator<String>
{

    public int compare(String x, String y)
    {
        // Assume neither string is null. Real code should
        // probably be more robust
        if (x.length() < y.length())
        {
            return 1;
        }
        if (x.length() > y.length())
        {
            return -1;
        }
        return 0;
    }
}    // Test.java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test
{
    public static void main(String[] args)
    {
        Comparator<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
        queue.add("short");
        queue.add("very long indeed");
        queue.add("medium");
        while (queue.size() != 0)
        {
            System.out.println(queue.remove());
        }
    }
}

9. Phân tích hoạt động của bài toán Producer – Consumer trong lập trình đa luồng

(multi-thread)

 
 



P- C Ko đồng bộ:
       
P – C Đồng bộ:
 
 

10. Transaction. Yn và cho ví dụ minh họa:
• Mặc định, sau khi mỗi câu lệnh SQL được thực thi qua
JDBC, dữ liệu sẽ được cập nhật ngay vào CSDL
• Có những trường hợp, ta muốn dữ liệu chỉ được cập
nhật vào CSDL sau khi một số câu lệnh SQL được thực
hiện
• Vídụ: đối với trang ứng dụng bán hàng qua mạng, để
CSDL được thống nhất, ta chỉ muốn lưu các dữ liệu
liên quan tới một đơn đặt hàng cùng một lúc
• Một nhóm các câu lệnh như thế được gọi là một giao
dịch (transaction)

CÀI ĐẶT GIAO DỊCH
•Trước hết, phải không dùng chế độ COMMIT tự  động từ Connection object
conn.setAutoCommit(false);
•Thực hiện các câu lệnh trong một giao dịch
•Thực hiện COMMIT (lưu) CSDL
conn.commit();
•Nếu không cần dùng ở chế độ giao dịch nữa, ta nên trả lại chế độ COMMIT tự động
conn.setAutoCommit(true);
 

11. Dễ
12. Mô hình Client/ Server sử dụng giao thức có kết nối
 
 
 

Bạn đang đọc truyện trên: Truyen2U.Top

Tags: