💡 Generic의 사용이유와 사용법
📘 코드 재사용성과 타입 안정성
제네릭 사용 이유
제네릭 클래스
// 제네릭 클래스 - T는 타입 파라미터
public class GenericClass<T> { // <T> 로 선언
private T item;
public GenericClass(T item){
this.item = item;
}
public T getItem(){
return item;
}
}
// 메인 클래스(호출)
public class Main {
public static void main(String[] args){
// 제네릭 활용
// 1. 재사용성 보장 - 다양한 타입 저장
GenericClass<String> genericBox1 = new GenericClass<>("ABC");
GenericClass<Integer> genericBox2 = new GenericClass<>(123);
GenericClass<Double> genericBox3 = new GenericClass<>(0.123);
// 2. 타입 안정성 보장 - 컴파일시
String strItem = genericBox1.getItem();
Integer intItem = genericBox2.getItem();
Double douItem = genericBox3.getItem();
}
}
제네릭 메서드
public class Util {
//메서드 선언부에 <T> 선언 - 매개변수에 선언
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
//하나의 메서드로 형변환 없이 String, Integer 사용 가능
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4};ㄴ
String[] strArray = {"A", "B", "C"};
Util.printArray(intArray); // 1 2 3 4
Util.printArray(strArray); // A B C
}
}