제네릭을 사용하는 이유

SangHun Park·2022년 8월 29일
0
  • 컴파일 시점에 강한 타입 체크가 가능하다.
    강한 타입 체크? -> 타입이 강하지 않으면 런타임 시점에 에러가 발생하여 오류를 찾아내기 어려운 상황이 발생한다. 강한 타입 체크를 사용할 경우 컴파일 시점에 오류를 쉽게 찾아낼 수 있다.
    (런타임은 실제 Application이 실행되는 과정에서 발생되는 반면 컴파일은 실행 이전에 오류를 발생되기 때문에 상대적으로 더 안전하다.)

  • 캐스팅 작업을 제거할 수 있다.
    제네릭을 사용하면 타입을 선언하여 처리하기 때문에 캐스팅 작업이 생략된다.

  • 프로그래머에게 제네릭 알고리즘을 구현 가능하게 한다.
    제네릭을 사용하게 되면 프로그래머는 다른 타입들에 대한 처리 구현이 가능하고 커스터마이징 처리 또한 가능하며 타입 세이프하며 가독성 측면에서 좋다.


https://docs.oracle.com/javase/tutorial/java/generics/why.html

Why Use 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.

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.
    The following code snippet without generics requires casting:

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

    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
  • 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.

0개의 댓글