Thuta Learning
Java
AdvancedProgrammingအခြေခံ

Generics

Javaသင်ခန်းစာ 2435 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • <T> ပါတဲ့ generic method နဲ့ generic class ကို ရေးပြီး compiler ကို type infer လုပ်ခိုင်းနိုင်ဖို့
  • <T extends Comparable<T>> လို bound နဲ့ T ရဲ့ method တွေကို သုံးခွင့်ရအောင် လုပ်နိုင်ဖို့
  • List<Integer> က List<Number> မဟုတ်တဲ့ အကြောင်း (invariance) နဲ့ ? extends / ? super ကို ရွေးနိုင်ဖို့
  • Type erasure ကြောင့် new T(), List<int>, raw type တွေ ဘာကြောင့် ပြဿနာဖြစ်လဲ ရှင်းပြနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Generics ကို ရိုးရိုးလေး ပြောရရင်

Generics က class ဒါမှမဟုတ် method တစ်ခုကို type တစ်ခုအတွက် ချုပ်ကိုင်မထားဘဲ "type T တစ်ခုခု" အတွက် ရေးခွင့်ပေးပါတယ်။ List<String> ဆိုတာ "String တွေပဲ ထည့်လို့ရတဲ့ list" ဖြစ်ပြီး List<Integer> က Integer တွေအတွက်ပါ — code တစ်ခုတည်း၊ type မတူတဲ့ version အများကြီးပါ။ Compiler က မှားတဲ့ type ထည့်တာကို program မ run ခင်ကတည်းက ဖမ်းပေးပါတယ်။

စားသောက်ဆိုင်က label ကပ်ထားတဲ့ ဗူးတွေကို စဉ်းစားကြည့်ပါ။ "ဆား" label ကပ်ထားတဲ့ ဗူးထဲ သကြား ထည့်မိရင် ဟင်းချက်တဲ့အထိ မသိရပါဘူး။ Generics ရှိတဲ့ ဗူးကတော့ label မကိုက်တဲ့ ပစ္စည်းကို ထည့်ခွင့်ကို တံခါးဝမှာတင် ငြင်းပါတယ်၊ ပြန်ထုတ်တဲ့အခါလည်း ဘာထွက်လာမလဲ သေချာ သိပါတယ်။

Problem → Why → Solution

ပြဿနာ: raw type နဲ့ cast တွေ

Java 5 မတိုင်ခင်က collection တွေမှာ type parameter မရှိခဲ့ပါဘူး၊ ArrayList က Object ကိုပဲ သိမ်းပြီး ပြန်ထုတ်တိုင်း cast လုပ်ရပါတယ်။ အဲဒီ ပုံစံ (raw type) ကို ယနေ့ထိ ရေးလို့ ရနေသေးလို့ ဟောင်းနွမ်းတဲ့ tutorial ကို ကူးတဲ့သူတွေ ရေးမိဆဲပါ။ အောက်က code က compile ဖြစ်ပါတယ်၊ ဒါပေမဲ့ တစ်နေရာမှာ number တစ်ခု မှားထည့်မိတာကို ဘယ်သူမှ မသိဘဲ နောက်ဆုံး cast မှာ ClassCastException နဲ့ ပေါက်ကွဲပါတယ်။

RawList.java
List names = new ArrayList();          // raw type: holds Object
names.add("Ada");
names.add(42);                         // nothing stops this

String second = (String) names.get(1); // ClassCastException at runtime

Type အမှားကို compile time ကို ရွှေ့ပါ

Raw list က ဘာ type ထည့်ထားလဲ ဆိုတဲ့ အသိကို လုံးဝ မထိန်းထားလို့ compiler က ကူညီလို့ မရပါဘူး၊ error က crash ဖြစ်တဲ့နေရာ (cast) မှာ ပေါ်ပြီး အမှားလုပ်တဲ့နေရာ (add) မှာ မပေါ်ပါဘူး။ List<String> လို့ ရေးလိုက်ရင် names.add(42) က compile error ဖြစ်သွားပြီး get() က String ကို တိုက်ရိုက် ပြန်ပေးလို့ cast လည်း မလိုတော့ပါဘူး။

Core concept: type parameter၊ bound၊ wildcard၊ erasure

Type parameter ကို angle bracket နဲ့ ကြေညာပါတယ်။ Generic class မှာ class နာမည်နောက်မှာ ထားပြီး (class Box<T>)၊ generic method မှာတော့ return type ရှေ့မှာ ထားပါတယ် (static <T> T first(List<T> values))။ ခေါ်တဲ့အခါ compiler က argument တွေကနေ T ကို infer လုပ်ပါတယ်: first(List.of("Ada")) မှာ T က String ဖြစ်လို့ ရလဒ်ကို cast မလိုဘဲ String variable ထဲ ထည့်လို့ ရပါတယ်။ Object ဆောက်တဲ့အခါလည်း new ArrayList<>() လို diamond နဲ့ ရေးရင် type ကို ဘယ်ဘက်ခြမ်းကနေ infer လုပ်ပါတယ်။ ဓလေ့အရ type parameter တွေကို စာလုံးကြီး တစ်လုံးတည်းနဲ့ ပေးလေ့ရှိပါတယ်: type အတွက် T၊ element အတွက် E၊ map ရဲ့ key နဲ့ value အတွက် K နဲ့ V ပါ။

Bound မပါတဲ့ T က ဘာမဆို ဖြစ်နိုင်လို့ Object ရဲ့ method တွေကိုပဲ ခေါ်လို့ ရပါတယ်။ <T extends Comparable<T>> လို bound ထည့်လိုက်ရင် T တိုင်းမှာ compareTo() ရှိကြောင်း compiler က သိလို့ max လို method ရေးလို့ ရလာပြီး Comparable မဟုတ်တဲ့ type နဲ့ ခေါ်ရင် compile error ဖြစ်ပါတယ်။ ဒီနေရာမှာ extends က class ရော interface ရော နှစ်မျိုးလုံးအတွက် သုံးပါတယ်။

Generic type တွေက invariant ဖြစ်ပါတယ်: Integer က Number ရဲ့ subtype ဖြစ်ပေမဲ့ List<Integer> က List<Number> ရဲ့ subtype မဟုတ်ပါဘူး။ ခွင့်ပြုခဲ့ရင် List<Number> reference ကနေ Double ကို Integer list ထဲ ထည့်လို့ ရသွားမှာမို့ပါ။ ပြောင်းလွယ်ပြင်လွယ် လိုရင် wildcard ကို သုံးပါ: List<? extends Number> က Number subtype list တိုင်းကို ဖတ်ဖို့ လက်ခံပြီး (producer)၊ List<? super Integer> က Integer တွေ ထည့်ဖို့ လက်ခံပါတယ် (consumer)။ ဒါကို PECS — Producer Extends, Consumer Super — လို့ မှတ်ပါ။

text
Why List<Integer> cannot be a List<Number>
------------------------------------------
List<Integer> ints = new ArrayList<>();
List<Number>  nums = ints;     // compile error -- but suppose it worked:
nums.add(3.14);                // a Double is now inside ints
Integer i = ints.get(0);       // ClassCastException

List<? extends Number> readOnly = ints;   // OK: read Numbers, add nothing
List<? super Integer>  sink = nums;       // OK: add Integers

Java generics ကို type erasure နဲ့ အကောင်အထည်ဖော်ထားပါတယ်: compiler က type တွေကို စစ်ပြီးနောက် type argument တွေကို ဖျက်ပစ်လို့ runtime မှာ List<String> နဲ့ List<Integer> က List တစ်မျိုးတည်း ဖြစ်သွားပါတယ်။ ဒါကြောင့် new T(), new T[10] ကို ရေးလို့ မရသလို primitive type တွေကိုလည်း type argument အဖြစ် သုံးလို့ မရပါဘူး၊ List<int> အစား List<Integer> ကို သုံးပြီး autoboxing က int နဲ့ Integer ကြား ပြောင်းပေးပါတယ်။

Generics က compile time ကတိ
  1. <T> က type အတွက် ကွက်လပ်
  2. ခေါ်တဲ့နေရာက T ကို ဖြည့် (infer)
  3. Compiler က add/get တိုင်းကို စစ်
  4. Runtime မှာ T ကို ဖျက်ပြီးသား (erasure)

Raw type သုံးလိုက်တာနဲ့ ဒီ ကတိကို ကိုယ်တိုင် ဖျက်လိုက်တာပါ၊ compiler က warning ပဲ ပေးပြီး runtime crash ကို သင့်ဆီ ပြန်လွှဲပါတယ်။

အထွေထွေ ပုံစံ

java
class Container<T> { T get() { ... } }               // generic class

static <T> T pick(List<T> items) { ... }             // generic method

static <T extends Comparable<T>> T best(List<T> xs)  // bounded

static double total(List<? extends Number> source)   // producer: read

static void fill(List<? super Integer> target)       // consumer: write

Container<String> c = new Container<>();             // diamond inference

Class မှာ type parameter ကို နာမည်နောက်မှာ၊ method မှာ return type ရှေ့မှာ ကြေညာပါ။ T ရဲ့ method တွေ လိုရင် extends နဲ့ bound ထည့်ပြီး parameter က ဖတ်ရုံပဲ ဖတ်မလား ရေးမလားပေါ် မူတည်ပြီး ? extends ဒါမှမဟုတ် ? super ကို ရွေးပါ။

Worked example: type ကို ထိန်းထားတဲ့ first()

first() က ဘယ် element type ရှိတဲ့ list ကိုမဆို လက်ခံပြီး အဲဒီ type အတိုင်း ပြန်ပေးပါတယ်။ main က String list နဲ့ ခေါ်လို့ T က String ဖြစ်ပြီး ရလဒ်ကို cast မလိုဘဲ String name ထဲ ထည့်ပါတယ်။ List အလွတ်ကို ငြင်းဖို့ စစ်ဆေးချက်လည်း ပါပါတယ်။

java
import java.util.List;

class Main {
    static <T> T first(List<T> values) {
        if (values.isEmpty()) throw new IllegalArgumentException("empty list");
        return values.getFirst();
    }

    public static void main(String[] args) {
        String name = first(List.of("Ada", "Linus"));
        System.out.println(name);
    }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Declare Tstatic <T> T first(List<T> values) {

    Return type ရှေ့က <T> က generic method ဖြစ်ကြောင်း ကြေညာပါတယ်။ Parameter က T list ဖြစ်ပြီး return type က T ဖြစ်လို့ input နဲ့ output type ချိတ်ဆက်သွားပါတယ်။

  2. Guard the empty caseif (values.isEmpty()) throw new IllegalArgumentException("empty list");

    List အလွတ်မှာ ပထမ element မရှိပါဘူး။ Message ရှင်းရှင်းနဲ့ စောစော fail ဖြစ်အောင် စစ်ထားပါတယ်။

  3. Typed returnreturn values.getFirst();

    getFirst() က Java 21 ရဲ့ SequencedCollection method ဖြစ်ပြီး T ကို ပြန်ပေးပါတယ်။ Java 21 မတိုင်ခင် version တွေမှာ values.get(0) ကို သုံးပါ။

  4. Inference at the call siteString name = first(List.of("Ada", "Linus"));

    Compiler က List<String> ကို မြင်ပြီး T = String လို့ infer လုပ်ပါတယ်။ (String) cast မလိုသလို Integer variable ထဲ ထည့်ကြည့်ရင် compile error ရပါမယ်။

You should see
Ada

Generic class နဲ့ bounded type parameter

Box<T> က value တစ်ခုကို သိမ်းထားတဲ့ generic class ပါ။ max() ကတော့ T ကို Comparable<T> နဲ့ ကန့်သတ်ထားလို့ compareTo() ကို ခေါ်လို့ ရပါတယ်။ Integer နဲ့ String နှစ်ခုလုံး Comparable ဖြစ်လို့ max() က နှစ်မျိုးလုံးနဲ့ အလုပ်လုပ်ပါတယ်။

Boxes.java
import java.util.List;

public class Boxes {
  public static void main(String[] args) {
    Box<String> label = new Box<>("fragile");
    String text = label.get();                 // no cast needed
    System.out.println(text.toUpperCase());

    System.out.println(max(List.of(3, 9, 4)));
    System.out.println(max(List.of("pear", "apple", "fig")));
  }

  static <T extends Comparable<T>> T max(List<T> values) {
    T best = values.getFirst();
    for (T value : values) {
      if (value.compareTo(best) > 0) {
        best = value;
      }
    }
    return best;
  }
}

class Box<T> {
  private final T value;

  Box(T value) {
    this.value = value;
  }

  T get() {
    return value;
  }
}

Output က FRAGILE၊ 9၊ pear ဖြစ်ပါတယ် (string တွေကို အက္ခရာစဉ်အတိုင်း နှိုင်းယှဉ်လို့ "pear" က အကြီးဆုံးပါ)။

Wildcard: ? extends နဲ့ ? super

sum() က list ထဲက number တွေကို ဖတ်ရုံပဲ ဖတ်လို့ ? extends Number ကို သုံးပြီး List<Integer> ကော List<Double> ကော လက်ခံပါတယ်။ addDefaults() ကတော့ Integer တွေကို ထည့်ရုံပဲ ထည့်လို့ ? super Integer ကို သုံးပြီး List<Number> ကော List<Object> ကော လက်ခံပါတယ်။ Wildcard မပါဘဲ List<Number> လို့ပဲ ရေးခဲ့ရင် method နှစ်ခုလုံးက အဲဒီ type အတိအကျကိုပဲ လက်ခံပါလိမ့်မယ်။

Wildcards.java
import java.util.ArrayList;
import java.util.List;

public class Wildcards {
  public static void main(String[] args) {
    System.out.println(sum(List.of(1, 2, 3)));         // List<Integer>
    System.out.println(sum(List.of(0.5, 1.5)));        // List<Double>

    List<Number> numbers = new ArrayList<>();
    List<Object> objects = new ArrayList<>();
    addDefaults(numbers);
    addDefaults(objects);
    System.out.println(numbers + " " + objects);
  }

  static double sum(List<? extends Number> source) {    // producer: read only
    double total = 0;
    for (Number n : source) {
      total += n.doubleValue();
    }
    return total;
  }

  static void addDefaults(List<? super Integer> target) {   // consumer: write
    target.add(1);
    target.add(2);
  }
}

ဒီ program က 6.0၊ 2.0၊ [1, 2] [1, 2] ကို print ထုတ်ပါတယ်။ sum() ထဲမှာ source.add(4) လို့ ရေးကြည့်ရင် compile error ရပါတယ် — ? extends Number list က တကယ်တော့ List<Double> ဖြစ်နေနိုင်လို့ compiler က ဘာကိုမှ (null မှလွဲ) ထည့်ခွင့် မပေးပါဘူး။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ generics

Generics ကို ကိုယ်တိုင် class တစ်ခုမှ မရေးရသေးခင်ကတည်းက နေ့တိုင်း သုံးနေပြီးသားပါ။ List<Order>, Map<String, Customer>, Optional<User> တွေက ဘာ type သယ်ထားလဲ ကြေညာထားလို့ IDE က autocomplete ပေးနိုင်ပြီး compiler က type မကိုက်တာကို ဖမ်းပေးပါတယ်။ JDK ရဲ့ Collections.copy(List<? super T> dest, List<? extends T> src) signature ကိုယ်တိုင်က PECS ရဲ့ တကယ့် ဥပမာ တစ်ခုပါ။

  • API response wrapper: ApiResponse<T> တစ်ခုက ApiResponse<User>, ApiResponse<List<Order>> လို endpoint တိုင်းအတွက် envelope တစ်မျိုးတည်း ပေးပြီး payload type ကိုလည်း မပျောက်စေပါဘူး။
  • Repository base: Repository<T, ID> interface တစ်ခုက save(T), findById(ID) တို့ကို entity အမျိုးမျိုးအတွက် signature တစ်ခုတည်းနဲ့ ပေးပါတယ်။ Spring Data ရဲ့ CrudRepository<T, ID> က ဒီ ပုံစံအတိုင်း ဖြစ်ပါတယ်။
  • Utility method: groupBy, partition, retry<T>(Supplier<T>) လို helper တွေကို type parameter နဲ့ တစ်ခါ ရေးပြီး codebase တစ်ခုလုံးမှာ cast မပါဘဲ ပြန်သုံးပါတယ်။

အမှားများ

Generics နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Raw type သုံးပြီး warning ကို လျစ်လျူရှုခြင်း

List list = new ArrayList(); က compile ဖြစ်ပေမဲ့ compiler က "unchecked" warning ပေးပါတယ်။ အဲဒီ warning က type safety ပျောက်သွားပြီ ဆိုတဲ့ အချက်ပေးခြင်းပါ၊ မှားတဲ့ object ထည့်မိရင် နောက်မှ တခြားနေရာမှာ ClassCastException ဖြစ်ပါမယ်။ Type argument ကို အမြဲ ရေးပါ၊ type မသိရင် List<?> ကို သုံးပါ။

List<Integer> ကို List<Number> အဖြစ် ပို့ခြင်း

static double sum(List<Number> xs) ကို List<Integer> နဲ့ ခေါ်ရင် "incompatible types: List<Integer> cannot be converted to List<Number>" ရပါတယ်။ Cast ထည့်ပြီး ဖိအားပေးမယ့်အစား parameter ကို List<? extends Number> လို့ ပြောင်းပါ၊ method က ဖတ်ရုံပဲ ဖတ်တာမို့ အဲဒါက အဖြေမှန်ပါ။

Erasure ကို ဆန့်ကျင်ပြီး ရေးခြင်း

new T[10] က "generic array creation" error ဖြစ်ပြီး Object ကို instanceof List<String> နဲ့ စစ်ရင် "Object cannot be safely cast to List<String>" ဖြစ်ပါတယ်၊ runtime မှာ String ဆိုတဲ့ အချက်အလက် မရှိတော့လို့ပါ။ Array အစား List<T> ကို သုံးပြီး object အသစ် ဆောက်ဖို့ လိုရင် Supplier<T> ဒါမှမဟုတ် Class<T> ကို parameter အဖြစ် ပို့ပါ။

Type argument တစ်ခုတည်း ကွာတဲ့ overload တွေ ရေးခြင်း

void process(List<String> x) နဲ့ void process(List<Integer> x) ကို တွဲရေးရင် "name clash: ... have the same erasure" ရပါတယ်။ Erasure ပြီးရင် နှစ်ခုလုံး process(List) ဖြစ်သွားလို့ပါ။ processNames(), processIds() လို နာမည် မတူအောင် ပေးပါ။

Mini challenge

Mini challenge: Pair, copyInto နဲ့ minOf

Generic အပိုင်းအစ သုံးခု ရေးပါ: တန်ဖိုး နှစ်ခုကို သိမ်းပြီး swap() နဲ့ ပြောင်းပြန်လှန်နိုင်တဲ့ generic record Pair<A, B>၊ source list ထဲက element တွေကို target list ထဲ ကူးထည့်တဲ့ copyInto() နဲ့ Comparable ဖြစ်တဲ့ type တိုင်းအတွက် အငယ်ဆုံး element ကို ရှာပေးတဲ့ minOf() ပါ။

  • Pair<A, B> ရဲ့ swap() က Pair<B, A> ကို ပြန်ပေးရမယ်
  • copyInto() က List<? super T> target နဲ့ List<? extends T> source ကို ယူရမယ် (PECS)
  • minOf() က <T extends Comparable<T>> bound ကို သုံးပြီး list အလွတ်ကို IllegalArgumentException နဲ့ ငြင်းရမယ်
  • Integer list နဲ့ Double list နှစ်ခုလုံးကို List<Number> တစ်ခုထဲ copyInto() နဲ့ ကူးပြပါ
GenericKit.java
import java.util.ArrayList;
import java.util.List;

public class GenericKit {
  public static void main(String[] args) {
    // TODO: build a Pair<String, Integer> ("Ada", 36), print it and its swap()
    // TODO: copy List.of(1, 2) and List.of(2.5) into one List<Number>, print it
    // TODO: print minOf for List.of(7, 3, 9) and List.of("pear", "apple", "fig")
  }

  // TODO: static <T> void copyInto(List<? super T> target, List<? extends T> source)

  // TODO: static <T extends Comparable<T>> T minOf(List<T> values)
}

// TODO: record Pair<A, B>(A first, B second) with a swap() method

ရလဒ်: Pair[first=Ada, second=36]၊ Pair[first=36, second=Ada]၊ [1, 2, 2.5]၊ 3၊ apple ဆိုတဲ့ line ငါးကြောင်း ထွက်ပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

Record တွေက generic ဖြစ်လို့ ရပါတယ်: record Pair<A, B>(A first, B second) { ... }။ swap() ထဲမှာ new Pair<>(second, first) လို့ ရေးရင် diamond က Pair<B, A> ကို infer လုပ်ပါတယ်။ copyInto() ထဲမှာ source က T တွေကို ထုတ်ပေးပြီး target က T တွေကို လက်ခံလို့ for loop တစ်ခုနဲ့ လုံလောက်ပါတယ်။

အဖြေ ကြည့်ရန်
GenericKit.java
import java.util.ArrayList;
import java.util.List;

public class GenericKit {
  public static void main(String[] args) {
    Pair<String, Integer> person = new Pair<>("Ada", 36);
    Pair<Integer, String> flipped = person.swap();
    System.out.println(person);
    System.out.println(flipped);

    List<Number> numbers = new ArrayList<>();
    copyInto(numbers, List.of(1, 2));     // T = Integer
    copyInto(numbers, List.of(2.5));      // T = Double
    System.out.println(numbers);

    System.out.println(minOf(List.of(7, 3, 9)));
    System.out.println(minOf(List.of("pear", "apple", "fig")));
  }

  static <T> void copyInto(List<? super T> target, List<? extends T> source) {
    for (T item : source) {
      target.add(item);
    }
  }

  static <T extends Comparable<T>> T minOf(List<T> values) {
    if (values.isEmpty()) {
      throw new IllegalArgumentException("minOf needs at least one value");
    }
    T smallest = values.get(0);
    for (T value : values) {
      if (value.compareTo(smallest) < 0) {
        smallest = value;
      }
    }
    return smallest;
  }
}

record Pair<A, B>(A first, B second) {
  Pair<B, A> swap() {
    return new Pair<>(second, first);
  }
}

Quick Quiz 1 / 3

List<Integer> ints = new ArrayList<>(); List<Number> nums = ints; ဘာဖြစ်မလဲ?

Quick Quiz 2 / 3

static <T extends Comparable<T>> T max(List<T> xs) ကို ဘယ် argument နဲ့ ခေါ်ရင် compile error ဖြစ်မလဲ?

Quick Quiz 3 / 3

Generic method ထဲမှာ T value = new T(); လို့ ဘာကြောင့် ရေးလို့ မရတာလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Type parameter (<T>) က class နဲ့ method တွေကို type အမျိုးမျိုးအတွက် cast မလိုဘဲ type-safe ဖြစ်စေပြီး compiler က T ကို များသောအားဖြင့် infer လုပ်ပါတယ်။
  • <T extends Bound> က T ရဲ့ method တွေကို သုံးခွင့်ပေးပြီး မကိုက်တဲ့ type ကို compile time မှာ ငြင်းပါတယ်။
  • Generic type တွေက invariant ဖြစ်ပါတယ်၊ ဖတ်ဖို့ ? extends၊ ရေးဖို့ ? super ကို သုံးပါ (PECS)။
  • Type erasure ကြောင့် new T(), generic array, List<int> မရပါဘူး၊ raw type ကို ဘယ်တော့မှ မသုံးပါနဲ့။

Java Language Specification, Java SE 25 — Oracle

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။