ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Practice Set 1 က ကားမောင်းသင်တုန်းက ကွင်းထဲမှာ ပတ်မောင်းတာလိုပါ။ Practice Set 2 ကတော့ လမ်းမပေါ် ထွက်မောင်းတာပါ။ Collection တွေ၊ inheritance နဲ့ exception တွေကို တစ်ခုချင်း သိပြီးပေမယ့် တစ်ပြိုင်နက် သုံးရတဲ့အခါမှ ကိုယ်တကယ် နားလည်လား မလည်လား ပေါ်လာပါတယ်။
Task လေးခုက ဈေးဝယ်စာရင်း၊ ဆိုင်ရဲ့ stock စာရင်း၊ ပုံသဏ္ဌာန် အမျိုးမျိုးရဲ့ ဧရိယာ၊ သုညနဲ့ စားမိတဲ့ error ကို ကိုင်တွယ်တာ ဖြစ်ပါတယ်။ Task တစ်ခုမစခင် ဆိုင်ရာ lesson ကို ခဏ ပြန်ကြည့်ပြီး ကိုယ်တိုင် အရင်ရေးပါ။ Reference answer ကို နောက်ဆုံးမှ ကြည့်ပါ။
Problem → Why → Solution
ပြဿနာ: collection တွေက ထင်သလို အလုပ်မလုပ်တဲ့အခါ
အောက်က attempt မှာ Integer list ထဲက value 10 ကို ဖယ်ချင်လို့ quantities.remove(10) လို့ ရေးထားပါတယ်။ Java က ဒါကို "index 10 က element ကို ဖယ်" လို့ နားလည်ပြီး IndexOutOfBoundsException ပစ်ပါတယ်။ ဒုတိယ loop က for-each လုပ်နေရင်း cart.remove() ကို ခေါ်လို့ ConcurrentModificationException တက်ပါတယ်။
Task 2 မှာလည်း inventory.get("grapes") က key မရှိလို့ null ပြန်ပေးပါတယ်။ အဲဒါကို int ထဲ ထည့်ပြီး ပေါင်းလိုက်ရင် NullPointerException ဖြစ်ပါမယ်။ Bug သုံးခုလုံးက collection ရဲ့ method တွေကို "နာမည်ကြည့်ပြီး ခန့်မှန်း" သုံးလို့ ဖြစ်တာပါ။
List<Integer> quantities = new ArrayList<>(List.of(10, 20, 30));
quantities.remove(10); // index 10! IndexOutOfBoundsException
List<String> cart = new ArrayList<>(List.of("rice", "eggs", "milk", "tea"));
for (String item : cart) {
if (item.startsWith("e")) {
cart.remove(item); // ConcurrentModificationException
}
}
int grapes = inventory.get("grapes"); // null -> NullPointerExceptionဘာကြောင့် ဒီလို ဖြစ်တာလဲ
List မှာ remove(int index) နဲ့ remove(Object o) ဆိုတဲ့ overload နှစ်ခု ရှိပြီး int literal 10 က remove(int) နဲ့ အတိအကျ ကိုက်လို့ compiler က အဲဒါကို ရွေးပါတယ်။ For-each loop ရဲ့ နောက်ကွယ်က iterator က list ကို ကိုယ်တိုင် မဟုတ်ဘဲ တခြားကနေ ပြင်လိုက်တာကို တွေ့ရင် exception ပစ်ပါတယ်။ Map ကတော့ missing key အတွက် exception မပစ်ဘဲ null ကို ပြန်ပေးလို့ ကိုယ်တိုင် စစ်ရပါတယ်။
Core concept: task တစ်ခုချင်းရဲ့ contract
Collection တွေနဲ့ exception တွေမှာ method တိုင်းက "ဒီလို ခေါ်ရင် ဒီလို ဖြစ်မယ်" ဆိုတဲ့ contract ရှိပါတယ်။ Task တစ်ခုချင်း မစခင် အဲဒီ contract ကို သိထားရင် bug အများစုကို ကြိုတင် ရှောင်နိုင်ပါတယ်။
Task 1: list ရဲ့ remove နှစ်မျိုး
shoppingList.remove("eggs") က value နဲ့ ရှာပြီး ပထမဆုံး တွေ့တာကို ဖယ်ကာ boolean ပြန်ပါတယ်။ shoppingList.remove(0) ကတော့ index 0 က element ကို ဖယ်ပြီး ဖယ်လိုက်တဲ့ element ကို ပြန်ပေးပါတယ်။ String list မှာ ရောထွေးဖို့ ခက်ပေမယ့် Integer list မှာ value ဖယ်ချင်ရင် remove(Integer.valueOf(10)) လို့ ရေးရပါတယ်။
Task 2: map ရဲ့ method ငါးခု
put() က key အသစ် ထည့်တာ ဒါမှမဟုတ် value အဟောင်းကို အစားထိုးတာ လုပ်ပါတယ်။ get() က missing key အတွက် null ပြန်ပြီး containsKey() က ရှိ/မရှိ စစ်ပါတယ်။ remove() က entry ကို ဖျက်ပြီး entrySet() က key-value pair တွေကို loop ပတ်ခွင့်ပေးပါတယ်။ HashMap က iteration order ကို အာမမခံလို့ reference answer မှာ LinkedHashMap ကို သုံးထားပါတယ်။ Method တွေက အတူတူပဲ ဖြစ်ပြီး ထည့်ခဲ့တဲ့ order အတိုင်း ပြန်ထွက်ပါတယ်။
Task 3: abstract method နဲ့ dynamic dispatch
abstract class Shape ကို new Shape() နဲ့ ဆောက်လို့ မရပါဘူး၊ subclass တွေကပဲ area() ကို ဖြည့်ပေးရပါတယ်။ Shape[] array ထဲက element တစ်ခုချင်းအတွက် s.area() ကို ခေါ်ရင် variable ရဲ့ type (Shape) ကို မကြည့်ဘဲ runtime မှာ object အစစ် (Circle ဒါမှမဟုတ် Rectangle) ရဲ့ version ကို run ပါတယ်။ ဒါကို dynamic dispatch လို့ ခေါ်ပါတယ်။
Task 4: finally ရဲ့ အာမခံချက်
divide(10, 2) က အောင်မြင်ရင် try ပြီး finally run ပါတယ်။ divide(7, 0) က throw လုပ်ရင် catch ပြီးမှ finally run ပါတယ်။ ဒါကြောင့် "Operation complete" က နှစ်ခါ ထွက်ပါတယ်။ int ကို 0 နဲ့ စားရင် Java က "/ by zero" ဆိုတဲ့ ArithmeticException ကို အလိုလို ပစ်ပေမယ့် b == 0 ကို ကြိုစစ်ပြီး ကိုယ်ပိုင် message ထည့်ထားတာက error ကို ပိုရှင်းစေပါတယ်။
- Method က ဘာကို ယူလဲ (index လား value လား)
- မရှိရင် ဘာပြန်လဲ (null လား exception လား)
- Order အာမခံလား
- Error ဖြစ်ရင် ဘယ်ကို ခုန်လဲ
မေးခွန်း လေးခု ဖြေနိုင်ရင် collection နဲ့ exception bug အများစုကို run မလုပ်ခင်ကတည်းက မြင်နိုင်ပါတယ်။
အခြေခံ ပုံစံ
list.remove(value); // by value (Object)
list.remove(index); // by position (int)
if (map.containsKey(key)) { int v = map.get(key); }
for (Map.Entry<K, V> e : map.entrySet()) { use(e.getKey(), e.getValue()); }
for (Base item : items) { item.behaviour(); } // subclass version runs
try { risky(); }
catch (SomeException e) { report(e.getMessage()); }
finally { cleanUp(); } // runs either wayremove ကို value နဲ့လား index နဲ့လား ရွေးပါ၊ get() မခေါ်ခင် key ကို စစ်ပါ၊ base type နဲ့ loop ပတ်ရင် subclass method run ပါတယ်၊ finally က အမြဲ run ပါတယ်။
Reference answer: task လေးခုလုံး
အောက်က reference answer က task လေးခုလုံးကို ဖြေထားပါတယ်။ main ပါတဲ့ Practice2 ကို Shape၊ Circle၊ Rectangle တို့ရဲ့ အပေါ်၊ file ရဲ့ အပေါ်ဆုံးမှာ ထားထားပါတယ်။ java Practice2.java နဲ့ run တဲ့အခါ Java က ပထမဆုံး class ထဲမှာ main ကို ရှာလို့ Shape က အရင်ရောက်နေရင် Shape ထဲမှာ main ကို ရှာပြီး fail ပါလိမ့်မယ်။ Inventory ကို LinkedHashMap နဲ့ ဆောက်ထားလို့ output order က run တိုင်း တူပါတယ်။
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Practice2 {
static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("cannot divide " + a + " by zero");
}
return a / b;
}
public static void main(String[] args) {
// Task 1: ArrayList shopping list
List<String> shoppingList = new ArrayList<>();
shoppingList.add("rice");
shoppingList.add("eggs");
shoppingList.add("milk");
shoppingList.add("tea");
shoppingList.remove("eggs"); // remove by value
shoppingList.remove(0); // remove by index: "rice"
System.out.print("Task 1: shopping list ->");
for (String item : shoppingList) {
System.out.print(" " + item);
}
System.out.println();
// Task 2: HashMap inventory (LinkedHashMap keeps insertion order)
Map<String, Integer> inventory = new LinkedHashMap<>();
inventory.put("apple", 40);
inventory.put("banana", 25);
inventory.put("mango", 10);
inventory.put("apple", 35); // same key: replaces 40
inventory.remove("banana");
System.out.println("Task 2: has banana? " + inventory.containsKey("banana")
+ ", apples = " + inventory.get("apple")
+ ", grapes = " + inventory.get("grapes"));
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println(" " + entry.getKey() + " x " + entry.getValue());
}
// Task 3: polymorphism over a Shape[] array
Shape[] shapes = { new Circle(5), new Rectangle(4, 6) };
for (Shape s : shapes) {
String kind = s.getClass().getSimpleName();
System.out.printf("Task 3: %s area = %.2f%n", kind, s.area());
}
// Task 4: try-catch-finally
int[][] pairs = { {10, 2}, {7, 0} };
for (int[] p : pairs) {
try {
int result = divide(p[0], p[1]);
System.out.println("Task 4: " + p[0] + " / " + p[1] + " = " + result);
} catch (ArithmeticException e) {
System.out.println("Task 4: error - " + e.getMessage());
} finally {
System.out.println(" Operation complete");
}
}
}
}
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private final double width;
private final double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Remove by value, then by index
shoppingList.remove(0); // remove by index: "rice""eggs" ကို value နဲ့ ဖယ်ပြီးနောက် list က [rice, milk, tea] ဖြစ်ပါတယ်။ remove(0) က index 0 မှာရှိတဲ့ rice ကို ဖယ်လို့ milk tea ပဲ ကျန်ပါတယ်။
- put() on an existing key
inventory.put("apple", 35); // same key: replaces 40apple ရှိပြီးသားမို့ entry အသစ် မဖြစ်ဘဲ 40 ကို 35 နဲ့ အစားထိုးပါတယ်။ LinkedHashMap မှာ key ရှိပြီးသားကို put လုပ်တာက order ကို မပြောင်းပါဘူး၊ apple က ပထမနေရာမှာပဲ ရှိနေပါတယ်။
- get() on a missing key
+ ", grapes = " + inventory.get("grapes"));grapes key မရှိလို့ get() က null ပြန်ပြီး string ထဲမှာ "null" လို့ ပေါ်ပါတယ်။ String နဲ့ ပေါင်းတာမို့ crash မဖြစ်ပေမယ့် int ထဲ ထည့်ရင် ဖြစ်ပါမယ်။
- One loop, two behaviours
for (Shape s : shapes) {s ရဲ့ type က Shape ဖြစ်ပေမယ့် s.area() က Circle အတွက် πr² (78.54)၊ Rectangle အတွက် width × height (24.00) ကို run ပါတယ်။ getClass().getSimpleName() က object အစစ်ရဲ့ class နာမည်ကို ပေးပါတယ်။
- finally after both outcomes
System.out.println(" Operation complete");ဒီ line က finally ထဲမှာ ရှိလို့ 10 / 2 အောင်မြင်တဲ့အခါရော 7 / 0 error ဖြစ်တဲ့အခါရော run ပါတယ်။ Output မှာ နှစ်ခါ ပေါ်တာ ဒါကြောင့်ပါ။
Task 1: shopping list -> milk tea
Task 2: has banana? false, apples = 35, grapes = null
apple x 35
mango x 10
Task 3: Circle area = 78.54
Task 3: Rectangle area = 24.00
Task 4: 10 / 2 = 5
Operation complete
Task 4: error - cannot divide 7 by zero
Operation completeသုညနဲ့ စားတာ: int နဲ့ double မတူပါ
Task 4 မှာ b == 0 ကို ကိုယ်တိုင် စစ်ထားပေမယ့် မစစ်ခဲ့ရင်လည်း 7 / 0 လို int division က "/ by zero" message နဲ့ ArithmeticException ကို Java က အလိုလို ပစ်ပါတယ်။ ဒါပေမယ့် 7.0 / 0 လို double division ကတော့ exception မပစ်ဘဲ Infinity ကို ပြန်ပေးပြီး 0.0 / 0 က NaN ကို ပြန်ပေးပါတယ်။
ဒါကြောင့် divide() ကို double နဲ့ ပြန်ရေးလိုက်ရင် catch block က ဘယ်တော့မှ မ run တော့ဘဲ Infinity တန်ဖိုးက နောက်ထပ် တွက်ချက်မှုတွေထဲ တိတ်တဆိတ် ဝင်သွားပါလိမ့်မယ်။ Divisor ကို ကြိုစစ်တာက type နှစ်မျိုးလုံးအတွက် ဘေးကင်းတဲ့ အလေ့အထပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
ဒီ task လေးခုက တကယ့် app တွေရဲ့ အပိုင်းအစလေးတွေပါ။ Shopping cart က List၊ product stock က Map၊ payment method တွေ (card၊ wallet၊ cash on delivery) က abstract class ဒါမှမဟုတ် interface ရဲ့ implementation တွေ ဖြစ်ပြီး checkout code က "ဘယ် payment လဲ" ကို if-else နဲ့ မစစ်ဘဲ pay() ကို ခေါ်ရုံပါပဲ။
finally ကို production မှာ file၊ database connection၊ lock လို resource တွေကို ပြန်လွှတ်ဖို့ သုံးပါတယ်။ ဒါပေမယ့် AutoCloseable ဖြစ်တဲ့ resource တွေအတွက်တော့ try-with-resources က ပိုတိုပြီး close() ကို မေ့စရာ မရှိလို့ ခေတ်ပေါ် Java code မှာ ပိုသုံးပါတယ်။ Test တွေမှာ map ရဲ့ output order ကို hard-code လုပ်ထားရင် HashMap ကြောင့် test တွေ မတည်မငြိမ် ဖြစ်တတ်လို့ order လိုရင် LinkedHashMap ဒါမှမဟုတ် TreeMap ကို ရွေးပါ၊ ဒါဆိုရင် test တွေက ဘယ်စက်မှာမဆို pass ဖြစ်ပါလိမ့်မယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Integer list မှာ remove(10) ကို value လို့ ထင်တာ
List<Integer> မှာ remove(10) က index 10 ကို ဖယ်ပါတယ်။ Value ဖယ်ချင်ရင် remove(Integer.valueOf(10)) လို့ ရေးပါ။ Index ထက် list ကျဉ်းနေရင် IndexOutOfBoundsException၊ ကျယ်နေရင်တော့ လူမှားကို ဖယ်ပါလိမ့်မယ်။
For-each loop ထဲမှာ list ကို ပြင်တာ
Loop လုပ်နေတဲ့ list ကို remove() နဲ့ ပြင်ရင် များသောအားဖြင့် ConcurrentModificationException တက်ပြီး တချို့ case မှာ element တစ်ခုကို exception မတက်ဘဲ ကျော်သွားတတ်ပါတယ်။ list.removeIf(...) ဒါမှမဟုတ် Iterator.remove() ကို သုံးပါ။
Map.of() ဒါမှမဟုတ် HashMap ရဲ့ order ကို အားကိုးတာ
HashMap ရဲ့ iteration order ကို Java က အာမမခံပါဘူး။ Map.of() နဲ့ Map.copyOf() က ဆောက်တဲ့ immutable map တွေရဲ့ order ကတော့ JVM run တစ်ခါနဲ့ တစ်ခါ ပြောင်းနိုင်ပါတယ်။ Output order အရေးကြီးရင် LinkedHashMap ဒါမှမဟုတ် TreeMap ကို သုံးပါ။
Divide ကို try block အပြင်မှာ ခေါ်တာ
int r = divide(7, 0); ကို try ရဲ့ အပေါ်မှာ ခေါ်ပြီး try ထဲမှာ r ကို print ထုတ်ရုံဆိုရင် exception က try မစခင် တက်ပြီး catch က ဘာမှ မဖမ်းရပါဘူး။ Exception ပစ်နိုင်တဲ့ call ကိုယ်တိုင်က try ထဲမှာ ရှိရပါမယ်။
Mini challenge
Task အသစ် သုံးခု: word count၊ stock နဲ့ shape အသစ်
Collection၊ exception နဲ့ inheritance ကို ထပ်လေ့ကျင့်ပါ။ (1) စာကြောင်းတစ်ကြောင်းထဲက စကားလုံးတွေကို TreeMap နဲ့ ရေတွက်ပါ။ (2) Stock class ရဲ့ take() က stock မလောက်ရင် custom checked OutOfStockException ပစ်ပြီး order တစ်ခုချင်းကို သီးခြား handle လုပ်ပါ။ (3) Square နဲ့ Triangle subclass တွေ ထပ်ထည့်ပြီး ဧရိယာ စုစုပေါင်းကို တွက်ပါ။
- Word count က စာလုံးအကြီးအသေး မခွဲဘဲ key တွေကို alphabetical order နဲ့ ပြရပါမယ်
- OutOfStockException က Exception ကို extend လုပ်ပြီး message မှာ ဘယ်လောက်လိုလဲ၊ ဘယ်လောက်ရှိလဲ ပါရပါမယ်
- Order တစ်ခု fail ဖြစ်လည်း နောက် order တွေ ဆက်လုပ်ရပါမယ်
- Stock snapshot ကို ထည့်ခဲ့တဲ့ order အတိုင်း ပြပါ (Map.copyOf() မသုံးပါနဲ့)
import java.util.*;
public class Practice2b {
static Map<String, Integer> wordCounts(String text) {
// TODO: TreeMap; split on whitespace; merge(word, 1, Integer::sum)
return new TreeMap<>();
}
public static void main(String[] args) {
// TODO: count words; run four orders through a Stock, each in its own
// try-catch; sum the areas of a Square and a Triangle
}
}
class OutOfStockException extends Exception { /* TODO: message constructor */ }
class Stock {
private final Map<String, Integer> items = new LinkedHashMap<>();
void add(String item, int qty) { /* TODO */ }
void take(String item, int qty) throws OutOfStockException { /* TODO */ }
}
// TODO: abstract class Shape, plus Square(side) and Triangle(base, height)ရလဒ်: {and=2, bat=1, cat=1, hat=1, the=3}၊ order နှစ်ခု အောင်မြင်ပြီး notebook နဲ့ stapler order နှစ်ခု fail ဖြစ်၊ left: {pen=0, notebook=3} နဲ့ total area = 19.0 ထွက်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
counts.merge(word, 1, Integer::sum) က key မရှိရင် 1 ထည့်ပြီး ရှိရင် +1 လုပ်ပါတယ်။ take() ထဲမှာ items.getOrDefault(item, 0) နဲ့ မရှိတဲ့ item ကို 0 အဖြစ် ယူပြီး qty ထက် နည်းရင် throw လုပ်ပါ။
အဖြေ ကြည့်ရန်
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Practice2b {
static Map<String, Integer> wordCounts(String text) {
Map<String, Integer> counts = new TreeMap<>(); // sorted by key
for (String word : text.toLowerCase().split("\s+")) {
counts.merge(word, 1, Integer::sum);
}
return counts;
}
public static void main(String[] args) {
System.out.println(wordCounts("The cat and the hat and THE bat"));
Stock stock = new Stock();
stock.add("pen", 10);
stock.add("notebook", 3);
String[][] orders = {
{"pen", "4"}, {"notebook", "5"}, {"stapler", "1"}, {"pen", "6"},
};
for (String[] order : orders) {
try {
stock.take(order[0], Integer.parseInt(order[1]));
System.out.println("took " + order[1] + " " + order[0]);
} catch (OutOfStockException e) {
System.out.println("order failed: " + e.getMessage());
}
}
System.out.println("left: " + stock.snapshot());
List<Shape> shapes = List.of(new Square(3), new Triangle(4, 5));
double total = 0;
for (Shape s : shapes) {
total += s.area();
}
System.out.println("total area = " + total);
}
}
class OutOfStockException extends Exception {
OutOfStockException(String message) {
super(message);
}
}
class Stock {
private final Map<String, Integer> items = new LinkedHashMap<>();
void add(String item, int qty) {
items.merge(item, qty, Integer::sum);
}
void take(String item, int qty) throws OutOfStockException {
int have = items.getOrDefault(item, 0);
if (have < qty) {
throw new OutOfStockException(item + ": wanted " + qty + ", have " + have);
}
items.put(item, have - qty);
}
Map<String, Integer> snapshot() {
return new LinkedHashMap<>(items); // a copy, still in insertion order
}
}
abstract class Shape {
abstract double area();
}
class Square extends Shape {
private final double side;
Square(double side) { this.side = side; }
@Override double area() { return side * side; }
}
class Triangle extends Shape {
private final double base;
private final double height;
Triangle(double base, double height) { this.base = base; this.height = height; }
@Override double area() { return 0.5 * base * height; }
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- remove(Object) က value နဲ့၊ remove(int) က index နဲ့ ဖယ်ပါတယ်၊ Integer list မှာ သတိထားပါ
- Map ရဲ့ get() က missing key အတွက် null ပြန်လို့ containsKey() နဲ့ အရင်စစ်ပါ
- Order လိုရင် HashMap အစား LinkedHashMap ဒါမှမဟုတ် TreeMap ကို ရွေးပါ
- Base type နဲ့ loop ပတ်ရင် runtime မှာ subclass ရဲ့ method run ပါတယ်
- finally က success ရော failure ရော နှစ်ခုလုံးမှာ catch ရဲ့ နောက်မှာ run ပါတယ်