제네릭 클래스의 객체를 생성하고 사용하는 방법은 일반 클래스와 유사하지만, 객체를 생성할 때 타입 파라미터를 구체적인 타입으로 지정해주어야 합니다.
예를 들어, 앞서 언급한 GenericList 클래스를 기반으로 제네릭 클래스 객체를 생성하는 예제를 살펴보겠습니다.
public class GenericListExample {
public static void main(String[] args) {
// String 타입의 GenericList 객체 생성
GenericList<String> stringList = new GenericList<>();
stringList.addElement("Apple");
stringList.addElement("Banana");
stringList.addElement("Orange");
System.out.println("String List Size: " + stringList.size());
System.out.println("Element at index 1: " + stringList.getElement(1));
// Integer 타입의 GenericList 객체 생성
GenericList<Integer> integerList = new GenericList<>();
integerList.addElement(42);
integerList.addElement(99);
System.out.println("Integer List Size: " + integerList.size());
System.out.println("Element at index 0: " + integerList.getElement(0));
}
}
위의 예제에서 GenericList 클래스를 String과 Integer로 각각 인스턴스화하여 사용하고 있습니다.
주의할 점은 객체 생성 시에 타입 파라미터를 명시해주어야 한다는 것입니다. <String>과 <Integer>는 컴파일러에게 해당 객체가 어떤 타입을 다루는지 알려줍니다. 이를 통해 컴파일러는 타입 안정성을 보장하며, 코드에서 불필요한 형변환을 피할 수 있습니다.
또한, 제네릭 클래스를 사용할 때 타입 파라미터로는 참조 타입만 사용할 수 있습니다. 기본 타입(primitive type)은 사용할 수 없습니다. 만약 기본 타입을 사용해야 한다면, 해당 기본 타입의 래퍼 클래스(Wrapper Class)를 사용하면 됩니다.
With ChatGPT
'JAVA > 포스팅' 카테고리의 다른 글
자바 제네릭스 와일드 카드 (0) | 2023.11.19 |
---|---|
자바 제네릭 제한된 클래스 (0) | 2023.11.19 |
자바 제네릭 클래스의 선언 (0) | 2023.11.19 |
자바 제네릭스(Generics) (0) | 2023.11.19 |
자바 컬렉션 프레임워크 Collections (0) | 2023.11.19 |