※ 제네릭
자료구조에 특정자료형만 들어가게 정할 수 있음 .<> Generic 풀네임은 element generic, c의 개념 가져온것
public class Box {
public Object content;
}
Box는 다양한 내용물을 저장해야 하므로 특정 클래스 타입으로 선언할 수 없다. Object 타입은 모든 클래스의 최상위 부모 클래스이다. 모든 객체는 부모 타입인 Object로 자동 타입 변환이 되므로 content 필드에는 어떤 객체든 대입이 가능하다.
하지만 이 방법을 쓰면 내용물이 String 타입이면 String content = (String) box.content; 로 강제 형변환을 통해 내용물을 얻어야 한다. 좋은 방법이 아님.
제네릭은 결정되지 않은 타입을 파라미터로 처리하고 실제 사용할 때 파라미터를 구체적인 타입으로 대체시키는 기능이다.
public class Box <T> {
public T content;
}
<T>는 T가 타입 파라미터임을 뜻하는 기호로, Box의 내용물로 String을 저장하고 싶다면 다음과 같이 Box를 생성할 때 타입 파라미터 T 대신 String으로 대체하면 된다.
Box<String> box = new Box<String>();
box.content = "안녕하세요.";
String content = box.content; // 강제 타입 변환 필요없이 "안녕하세요." 바로 얻을 수 있음
ex) Collection<String> c : String만 가능함.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
public class CollectionGenericTest {
public static void test(Collection<String> c) {
c.add("one");
// c.add(Integer.valueOf(2)); // <String>인데 int라서 compile 에러 발생
c.add("two");
c.add("one");
c.add("four");
c.add("five");
System.out.println("요소갯수:" + c.size());
System.out.println(c);
c.remove("one");
System.out.println("one객체 삭제됨");
for(Object e : c) {
System.out.println("저장된 요소:" + e);
}
}
public static void main(String[] args) {
Collection<String> c;
System.out.println("----ArrayList----");
c = new ArrayList<>();
test(c);
System.out.println("----HashSet----");
test(new HashSet<>());
}
}
'언어 > Java' 카테고리의 다른 글
Product 예제 3 (1) | 2023.08.04 |
---|---|
Product 예제 2 (0) | 2023.08.04 |
향상된 for문 (0) | 2023.08.04 |
컬렉션 프레임워크(Java Collection Framework) (0) | 2023.08.04 |
어노테이션(Annotation) (0) | 2023.08.04 |