반응형
제네릭
- 의미
일반화된 클래스나 메소드
자료형 검사가능
제네릭은 다양한 타입의 객체들을 다루는 메서드나 컬렉션 클래스에 컴파일 시의 타입체크를 해주는 기능이다. – 자바의 정석
제네릭 예제
사용하지 않을때
ArrayList list = new ArrayList(); //제네릭을 사용하지 않을경우 list.add("test"); String temp = (String) list.get(0); //타입변환이 필요함 ArrayList list2 = new ArrayList(); //제네릭을 사용할 경우 list2.add("test"); temp = list2.get(0); //타입변환이 필요없음
위는 제네릭을 사용하지 않았을때이다. 안쓸때는 형변환이 필요하다,
- 사용할때
public class TestGeneric { public T sample; public void showYourType() { if(sample instanceof Integer) System.out.println("Integer 타입이군요!!"); else if(sample instanceof String) System.out.println("String 타입이군요!!"); } }
public class Main{
public static void main(String[] args)
{
TestGeneric stringType = new TestGeneric();
TestGeneric integerType = new TestGeneric();
stringType.sample = "Hello";
integerType.sample = 1;
stringType.showYourType();
integerType.showYourType();
}
}
- 위와같이 사용할수있다.
반응형
'자바' 카테고리의 다른 글
[Java] cannot be cast to java.lang.String 해결 (0) | 2023.06.26 |
---|---|
jdk-설치 (0) | 2022.09.21 |
이클립스 찾기 기능 단축키 (0) | 2021.04.01 |
컴파일하고 클래스파일이 있는곳 (0) | 2021.03.09 |
데이터 베이스에서 리스트 형 맵을 가져와서 가공하기 (0) | 2021.02.18 |
댓글