728x90
Generic ?
- 다양한 타입의 객체들을 다루는 메서드나 컬렉션 클래스에 컴파일 시 타입 체크를 해주는 기능
- 클래스 내부에서 지정하는 것이 아닌 외부에서 사용자에 의해 지정되는 것
//Generic 적용 x - Raw Type
ArrayList lists = new ArryList();
//Generic 적용 o
ArrayList<Member> lists = new ArrayList<>();
장점
- 잘못된 타입이 들어올 수 있는 것을 컴파일 단계에서 방지할 수 있다.
- 클래스 외부에서 타입을 지정해주기 때문에 따로 타입을 체크하고 변환해줄 필요가 없다.
- 비슷한 기능을 지원하는 경우 코드의 재사용성이 높아진다.
타입 종류
- → Type
- → Element
- → Key
- → Value
- → Number
public interface Map<K, V> {
/**
* Returns {@code true} if this map contains a mapping for the specified
* key. More formally, returns {@code true} if and only if
* this map contains a mapping for a key {@code k} such that
* {@code Objects.equals(key, k)}. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return {@code true} if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
*/
boolean containsKey(Object key);
/**
* Returns {@code true} if this map maps one or more keys to the
* specified value. More formally, returns {@code true} if and only if
* this map contains at least one mapping to a value {@code v} such that
* {@code Objects.equals(value, v)}. This operation
* will probably require time linear in the map size for most
* implementations of the {@code Map} interface.
*
* @param value value whose presence in this map is to be tested
* @return {@code true} if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
*/
boolean containsValue(Object value);
Raw Type
- 타입 파라미터가 없는 제네릭 타입
//Generic Type
Box<Integer> intBox = new Box<>();
//Raw Type
Box rawBox = new Box();
public class Box<T> {
public void set(T t){
}
}
- Raw Type의 슈퍼 클래스는 Raw Type이다. 상속 받지 않은 Raw Type의 생성자, 인스턴스 메서드, 인스턴스 필드는 Raw Type이다.
- Raw Type은 타입 파라미터만 지우는 것이 아니라 슈퍼 클래스의 타입 파라미터와 해당 클래스에 정의된 모든 타입 파라미터를 지운다.
List<String>
이라는 반환 타입이 Raw Type인List
로 바뀌는 것이다.
- Raw Type은 타입 파라미터만 지우는 것이 아니라 슈퍼 클래스의 타입 파라미터와 해당 클래스에 정의된 모든 타입 파라미터를 지운다.
- Raw Type은 자바에 제네릭이 도입되기 전 코드와 호환성을 보장하기 위한 것
Generic Compile
- 컴파일러는 컴파일 과정에서 올바른 유형이 사용되었는지 여부를 확인하기 위해 제네릭 사용
- 그 다음 유효성 검사가 완료되면 컴파일러는 제네릭 유형에 대한 참조를 삭제한 유형으로 대체하여 바이트 코드를 생성 → 바이트 코드 생성 시 제거됨
Generic Type Erasure
- 형식 매개 변수가 제한되지 않은 경우 제네릭 형식의 모든 형식의 매개 변수를
bound
또는Object
로 변경한다. 따라서 생성된 바이트 코드에는 일반 클래스, 인터페이스 및 메서드만 포함된다.
- 직접 명시하지 않은 타입 매개변수인 Raw Type은 컴파일시에 Object로 대체된다.
- 타입 안정성을 위해 Bridge Method를 만들기도 한다.
public class IntegerStack extends Stack<Integer>{
public Integer push(Integer value){
super.push(value);
return value;
}
}
public class IntegerStack extends Stack{
// Bridge Method
public Integer push(Object value){
return push(Integer) value);
}
public Integer push(Integer value){
return super.push(value);
}
}
- 위와 같이 Object를 Integer로 캐스팅 해줌으로써 제네릭소거로 인해 발생하게 될 타입 불일치를 방지한다.
-Reference
https://stackoverflow.com/questions/19253174/are-generics-removed-by-the-compiler-at-compile-time
http://happinessoncode.com/2018/02/08/java-generic-raw-type/
'자바 스터디' 카테고리의 다른 글
객체 지향 ( Object - Oriented ) (0) | 2022.06.03 |
---|---|
리플렉션(Reflection) ? (0) | 2021.11.17 |
GC ( Garbage Collection ) ? (0) | 2021.11.10 |
자바의 컴파일 과정과 JVM에서 HEAP의 변화 (0) | 2021.11.03 |
JVM( Java Virtual Machine ) 이란 (0) | 2021.10.27 |