Thuta Learning
Java
AdvancedProgrammingbeginner

Generics

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

  • Generics ရဲ့language နဲ့JVM behavior ကိုရှင်းပြနိုင်ရန်
  • Normal, boundary, invalid နဲ့failure cases စမ်းနိုင်ရန်
  • Maintainable, testable Java code ရေးနိုင်ရန်

Type parameter သည်unsafe cast မလိုဘဲcaller ၏element type ကိုထိန်းပေးပါတယ်။

ပိုပြီးနားလည်ထားရမယ့် အချက်

Generics ကcompile-time type safety နဲ့reusable algorithms ပေးပါတယ်။ Java generics သည်invariant ဖြစ်ပြီးwildcards အတွက် producer-extends, consumer-super (PECS) ကိုသုံးကာtype erasure ကြောင့်runtime limitations ရှိတာကိုသိပါ။

လက်တွေ့မှာ ဘယ်လိုအသုံးချမလဲ

Generic `first` method နဲ့copy method ကိုbounded/wildcard forms ဖြင့်ရေးပြီးraw type warning နဲ့invalid assignment ကိုcompiler ကဖမ်းကြောင်းစမ်းပါ။

ဒီသင်ခန်းစာပြီးရင်

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);
    }
}
You should see
Ada

ကိုယ်တိုင်စမ်းကြည့်ရန်

Generic `first` method နဲ့copy method ကိုbounded/wildcard forms ဖြင့်ရေးပြီးraw type warning နဲ့invalid assignment ကိုcompiler ကဖမ်းကြောင်းစမ်းပါ။

Common Mistake သတိပေးချက်

`List<Integer>` သည်`List<Number>` subtype ဖြစ်သည်ဟုယူဆခြင်း သို့မဟုတ်raw types ဖြင့်warnings ကိုဖျောက်ခြင်း။

Java Language Specification, Java SE 25Oracle

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • `List<Integer>` သည်`List<Number>` subtype ဖြစ်သည်ဟုယူဆခြင်း သို့မဟုတ်raw types ဖြင့်warnings ကိုဖျောက်ခြင်း။
  • Sample output တစ်ခုမှန်ရုံဖြင့် null, boundary, resource နဲ့concurrency behavior အားလုံးမှန်ပြီဟုယူဆခြင်း။

လက်တွေ့လေ့ကျင့်ခန်း

Generic `first` method နဲ့copy method ကိုbounded/wildcard forms ဖြင့်ရေးပြီးraw type warning နဲ့invalid assignment ကိုcompiler ကဖမ်းကြောင်းစမ်းပါ။

You'll know it worked when: Ada