By GokiSoft.com| 20:25 12/08/2021|
Java Advanced

[Share Code] Tìm hiểu Collections + + Map - Generic - Lập trình Java - C2010L



Nội dung kiên thức
- Exception:
- Collections
	- List: ArrayList, Vector, LinkedList
	- Set: HashSet, TreeSet
	- Map: HashMap
	- Stack & Queue
		Stack (LIFO) -> LAST IN FIRST OUT
		1 -> 2 -> 5 -> 7 -> 10
		push
		pop
			10
			1 -> 2 -> 5 -> 7
		pop
			7
			1 -> 2 -> 5
		...

		Queue (FIFO) -> FIRST IN FIRST OUT
		10 -> 7 -> 5 -> 2 -> 1
		push
		pop
			1
			10 -> 7 -> 5 -> 2
		pop
			2
			10 -> 7 ->5
		...




#Test.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson01;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

/**
 *
 * @author Diep.Tran
 */
public class Test {
    public enum STATUS {
        INACTIVE(2, "ABC"), ACTIVE(6, "XYZ");

        public int value;
        public String ok;
        
        private STATUS(int value, String ok) {
            this.value = value;
            this.ok = ok;
        }
        
        public String toString() {
            return "value = " + value + ", ok = " + ok;
        }
    };
    
    public static void test(List<String> a, int k) {
        a.add("123");
        k += 10;
    }
    
    public static void main(String[] args) {
        STATUS st = STATUS.INACTIVE;
        
        System.out.println(st);
        
        //Tim hieu -> List: ArrayList, Vector, LinkedList
        ArrayList<String> a1 = new ArrayList<>();//ArrayList
        int x = 10;
        x = x + (x >> 1);
        System.out.println(">> " + x);
        x = x + (x >> 1);
        System.out.println(">> " + x);
        x = x + (x >> 1);
        System.out.println(">> " + x);
        //Phan tich ArrayList
        //Luu y: elementData -> Quan ly cac phan tu trong mang.
        //Ket qua:
        //1. Khoi tao doi tuong ArrayList -> elementData la 1 mang rong.
        //2. Khi goi toi ham add
        //      elementData -> empty() -> Khoi tao elementData gom 10 phan tu
        //      elementData -> khac rong
        //                          -> Tiep tuc add them vao -> khi mang con thua vung nho
        //                          -> Add phan tu thu 11 -> noi vung nho ra x >> 1 don vi (10 -> 15 -> 22 -> 33)
        System.out.println("Tim kieu ArrayList ...");
        //Them 1 phan tu
        a1.add("S1");
        a1.add("S2");
        a1.add("S3");
        int k = 11;
        test(a1, k);
        System.out.println("k = " + k);
        //Xoa phan tu
        a1.remove(1);
        //Chen vao 1 vi tri bat ky
        a1.add(1, "SS2");
        
        for (String v : a1) {
            System.out.println(">> " + v);
        }
        
        Vector<String> a2 = new Vector<>();
        //Phan tich:
        //Luu y: elementData -> Quan ly cac phan tu trong mang.
        //Ket qua:
        //1. Khoi tao doi tuong Vector -> elementData la 1 mang gom 10 phan tu.
        //2. Khi goi toi ham add
        //      elementData -> Them bt truong hop mang con thua vung nho
        //      elementData -> Thieu vung nho -> Tang gap doi vung nho hien tai (10 -> 20 -> 40 -> 80 ...)
        System.out.println("Tim kieu Vector ...");
        //Them 1 phan tu
        a2.add("S1");
        a2.add("S2");
        a2.add("S3");
        //Xoa phan tu
        a2.remove(1);
        //Chen vao 1 vi tri bat ky
        a2.add(1, "SS2");
        
        for (String v : a2) {
            System.out.println(">> " + v);
        }
        
        
        LinkedList<String> a3 = new LinkedList<>();
        System.out.println("Tim kieu LinkedList ...");
        //Them 1 phan tu
        a3.add("S1");
        a3.add("S2");
        a3.add("S3");
        //Xoa phan tu
        a3.remove(1);
        //Chen vao 1 vi tri bat ky
        a3.add(1, "SS2");
        
        for (String v : a3) {
            System.out.println(">> " + v);
        }
        
        Set<String> set = new HashSet<>();
        set.add("asds");
        set.add("324");
        
        for (String v : set) {
            System.out.println(v);
        }
        
        //Map -> key : value
        Map<String, String> map = new HashMap<>();//Hoat dong nhu localStorage (js), COOKIE, SESSION -> PHP
        map.put("K1", "Xin chao 1");
        map.put("K1", "Xin chao 12");
        map.put("K1", "Xin chao 123");//Lay gia tri cuoi cung.
        map.put("K2", "Xin chao 2");
        map.put("K3", "Xin chao 3");
        
        String v = map.get("K1");
        System.out.println(v);
        
        Map<String, Student> mapStudent = new HashMap<>();
        mapStudent.put("R01", new Student("A", "SASDSA"));
        mapStudent.put("R02", new Student("B", "SASDSA"));
        mapStudent.put("R03", new Student("C", "SASDSA"));
        
        Student std = mapStudent.get("R02");
        System.out.println(std);
        //Yeu cau du an -> su dung lam sao toi uu nhat -> exp -> Biet dc luc nao dung cai nao thi optimize.
        
        for (Map.Entry<String, Student> entry : mapStudent.entrySet()) {
            String key = entry.getKey();
            Student value = entry.getValue();
            System.out.println("key: " + key);
            System.out.println(value);
        }
        
        for (String key : mapStudent.keySet()) {
            Student obj = mapStudent.get(key);
            System.out.println(obj);
        }
    }
}


#Student.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson01;

/**
 *
 * @author Diep.Tran
 */
public class Student {
    String name, rollno;

    public Student(String name, String rollno) {
        this.name = name;
        this.rollno = rollno;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", rollno=" + rollno + '}';
    }
    
    
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson01;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        //Viet chuong test phep
        Scanner scan = new Scanner(System.in);
        int x, y, s;
        
        System.out.println("Nhap x = ");
        x = Integer.parseInt(scan.nextLine());
        
        System.out.println("Nhap y = ");
        y = Integer.parseInt(scan.nextLine());
        
        //Logic -> Kiem tra dieu can than.
        if(y == 0) {
            System.err.println("Ko duoc phep chia cho 0");
            throw new ArithmeticException("Ko duoc phep chia cho 0");
        } else {
            s = x / y;
            System.out.println("s = " + s);
        }
        
        //Thuc hien bat error => try .. catch .. finally
        try {
            s = x / y;
            System.out.println("s = " + s);
        } catch(ArithmeticException e) {
            e.printStackTrace();
        } finally {
            //Su dung de giai phong tai nguyen du lieu
            System.out.println("Thanh cong & that bai -> finally luon dc thuc thi");
        }
        
        int[] t = {1, 5, 2};//length: 3, index: 0 -> 2
        try {
//            System.out.println("t[3] = " + t[3]);//Error logic -> fix can than.
        } catch(ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally...");
        }
        
        //Nhap so nguyen
        System.out.println("Test nhap so nguyen x = ");
        while(true) {
            try {
                x = Integer.parseInt(scan.nextLine().trim());
                break;
            } catch(Exception e) {
                System.out.println("Yeu cau nhap lai so nguyen x = ");
            }
        }
        
        System.out.println("x = " + x);
        
        //Bai toan:
        //Co 1 String s1 nhu sau
        String s1 = "Sinh vien aptech123 xin chao aptech123 abc aptech123";
        //Yeu cau kiem tra xem co xuat hien 1 substring (chuoi con) trong s1 tuan theo quy luat sau ko: ab -> a: [a->zA-Z]{2,10}, b: [0->9]{2,8}
        String s2 = "aptech123";//"[a-zA-Z]{2,10}[0-9]{2,8}";
        Pattern p = Pattern.compile(s2);
        Matcher m = p.matcher(s1);
        
        System.out.println("Chuoi tim thay: ");
        while(m.find()) {
            System.out.println(m.start() + " >> " + m.group());
        }
    }
}


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)