Generic Types

μ œλ„€λ¦­ νƒ€μž…μ€ μ œλ„€λ¦­ ν΄λž˜μŠ€λ‚˜ μΈν„°νŽ˜μ΄μŠ€μ˜ ν˜•μ‹μ— 따라 λ§€κ°œλ³€μˆ˜λ‘œ ν‘œμ‹œλœλ‹€.

class name <T1, T2, ..., Tn> { ... }

Naming Conversion

μ œλ„€λ¦­ νƒ€μž…μ€ 아무 λ¬Έμžμ—΄μ΄λ‚˜ μ‚¬μš©κ°€λŠ₯ν•˜μ§€λ§Œ 가독성을 μœ„ν•΄ 일반적으둜 λ‹€μŒ κ·œμΉ™μ„ λ”°λ₯Έλ‹€.

ν‚€ μ„€λͺ…
E μš”μ†Œ(Element)
K ν‚€(Key)
N 숫자(Number)
T νƒ€μž…(Type)
V κ°’(Value)
S, U, V λ‘λ²ˆμ§Έ, μ„Έλ²ˆμ§Έ, λ„€λ²ˆμ§Έμ— μ„ μ–Έλœ νƒ€μž…

The Diamond Java SE 1.7+

Java SE 7 이후 λ²„μ „μ—μ„œλŠ” 닀이아λͺ¬λ“œ μ—°μ‚°μžλ‘œ μΈν•œ μ΄ˆκΈ°ν™”κ°€ κ°€λŠ₯ν•˜λ‹€.

μ΄λŠ” μ œλ„€λ¦­ μΈμŠ€ν„΄μŠ€μ˜ 생성을 μžλ™μœΌλ‘œ μ μš©ν•΄μ€€λ‹€.

μ•„λž˜μ™€ 같은 읡λͺ… ν΄λž˜μŠ€μ—μ„œμ˜ μΈμŠ€ν„΄μŠ€ν™”λŠ” μ‚¬μš© λΆˆκ°€λŠ₯

List<String> list = new ArrayList<>() {};

Multiple Type Parameters

일반 ν΄λž˜μŠ€λŠ” 닀쀑 클래슀의 λ§€κ°œλ³€μˆ˜λ‘œ κ°€μ§ˆμˆ˜ μžˆλ‹€.

public interface Pair<K, V> {
  public K getKey();
  public V getValue();
}

public class OrderedPair<K, V> implements Pair<K, V> {
  private K key;
  private V value;

  public OrderedPair(K key, V value) {
    this.key = key;
    this.value = value;
  }

  public K getKey() { return key; }
  public V getValue() { return value; }
}

Parameterized Types

λ§€κ°œλ³€μˆ˜ν™” νƒ€μž… (Parameterized Type) μ‚¬μš©μ‹œμ—λŠ” λ‹€μŒ λ‘κ°€μ§€λ‘œ λ‚˜λ‰˜μ–΄μ§„λ‹€.

  • Actual Type Parameter

μ‹€ νƒ€μž… λ§€κ°œλ³€μˆ˜ (Actual Type Parameter) λŠ” <> μ•ˆμ— μ‹€μ‚¬μš© νƒ€μž… 자체λ₯Ό λͺ…μ‹œ ν•΄μ£ΌλŠ” 방식이닀.

List<String> list = new ArrayList<>();
  • Formal Type Parameter

ν˜•μ‹ νƒ€μž… λ§€κ°œλ³€μˆ˜ (Formal Type Parameter) νƒ€μž… λ§€κ°œλ³€μˆ˜λŠ” <> μ•ˆμ— λͺ…μ‹œμ  νƒ€μž…μ„ μ£ΌλŠ” 방식 이닀.

List<E> list = new ArrayList<>();

μ•„λž˜μ™€ 같이 λ§€κ°œλ³€μˆ˜λ₯Ό λ§€κ°œλ³€μˆ˜ν™” νƒ€μž…μœΌλ‘œ λŒ€μ²΄ κ°€λŠ₯ν•˜λ‹€.

OrderedPair<String, Box<Integer>> p = new OrderedPair<>("primes", new Box<Integer>(...));

Raw Types

Raw Type 은 νƒ€μž… νŒŒλΌλ©”ν„°κ°€ μ—†λŠ” μ œλ„€λ¦­ νƒ€μž…μ„ λ§ν•œλ‹€.







Β 







public class Message<T> {
  public List<String> getMessage() {
    return Arrays.asList("MESSAGE");
  }

  public static void main(String[] args) {
    Message message = new Message();

    for (String str : message.getMessage()) {
      System.out.println(str);
    }
  }
}

μœ„ μ½”λ“œμ—μ„œ message λ³€μˆ˜κ°€ Raw Type λ³€μˆ˜μΈλ°
Message ν΄λž˜μŠ€λŠ” μ œλ„€λ¦­ νƒ€μž…μœΌλ‘œ μ •μ˜λ˜μ—ˆμ§€λ§Œ λ³€μˆ˜ message λŠ” νƒ€μž… νŒŒλΌλ©”ν„° 없이 μ •μ˜λ˜μ—ˆλ‹€.

μ΄λŠ” μ œλ„€λ¦­μ˜ νƒ€μž… μ†Œκ±°λ‘œ μΈν•˜μ—¬ List<String> 이 μ•„λ‹Œ Raw Type List 둜 λœκ²ƒμ΄λ‹€.

νƒ€μž… μ†Œκ±°λŠ” J2SE 5 μ œλ„€λ¦­ μΆœν˜„ μ΄μ „μ˜ μ½”λ“œμ˜ ν˜Έν™˜μ„±μ„ 보μž₯ν•˜κΈ° μœ„ν•œ κ²ƒμœΌλ‘œ Raw Type 을 μ‚¬μš©ν•˜μ§€ 말아야 ν•œλ‹€.