원문

Generics는 왜 사용하는가 (Why Use Generics?)

간단히 말하면, generics는 타입을 클래스, 인터페이스, 메소드를 정의할 때 파라메터화 할 수 있다. 메소드 선언에 사용되는 파라미터 형식처럼, 타입 파라미터는 다른 입력값을 같은 코드를 재 사용할 수 있는 방법을 제시한다. 다른점은 형식 파라미터는 값이 입력이다, 타입 파라메터는 타입이 입력이다.
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

generic를 사용한 코드는 그렇지 않는 코드 대비 많은 장점을 가졌다:
Code that uses generics has many benefits over non-generic code

  • 컴파일 타임에 강력한 타입 체크를한다.
    Stronger type checks at compile time.

자바 컴파일러는 타입 안전성에 위반하는 코드가 있다면 일반적인 코드와 오류 이슈에 강한 타입 검사를 적용한다. 컴파일타임에 에러를 고치는 것은 런타임 에러를 고치는 것 보다 쉽다.

A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

  • 타입 캐스트 생략
    Elimination of casts.

    generics 없이 캐스팅이 필요한 코드 조각입니다.
    The following code snippet without generics requires casting:

    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);
    

    generics를 사용해서 코드를 다시 작성하면, 코드는 더이상 캐스팅이 필요 없어집니다.
    When re-written to use generics, the code does not require casting:

    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0);   // no cast
    
  • 프로그래머들이 일반적인 알고리즘을 구현하도록 지원한다.
    generics를 사용하면서 프로그래머들은 다양한 타입들의 콜렉션에서 동작하고, 수정가능하며, 더 안정적이고 읽기 쉬운 코드를 일반적인 알고리즘으로 구현할 수 있습니다.
    Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.