enum Scale {Good, Neutral, Bad}
public class Main{
public static void main(String[] args){
Scale scale= Scale.Good;
switch(scale){
case Good:
System.out.println("좋음");
break;
case Neutral:
System.out.println("중립");
break;
case Bad:
System.out.println("나쁨");
break;
}
}
}
---------------
좋음
<>
안에 들어갈 타입 지정타입 | 설명 |
---|---|
<T> | Type |
<E> | Element |
<K> | Key |
<V> | Value |
<N> | Number |
public class ClassName<T>{...}
public interface Interface<T>{...}
-----
* 제네릭 타입 두 개 생성(예-HashMap)
public className <T,K> {...}
public interface Interface<T,K>{...}
데이터 타입 외부 지정
class Entry<T>{
private T team1; // 가능
static T team2; // 불가능
extends ClassName
또는 &
을 사용해 제네릭스 제한 가능class ClassName<E>{
private E element; // 제네릭 타입 변수
void set(E element){ // 제네릭 파라미터 메소드
this.element = element;
}
E get(){// 제네릭 타입 반환 메소드
return element;
}
}
public class Main{
public static void main(String[] args) {
ClassName<String> a = new ClassValue<String>();
ClassName<Integer> b = new ClassValue<Integer>();
a.set("10");
b.set(10);
System.out.println("a data : "+a.get());
//반환된 변수 타입 출력
System.out.println("a E type : "+a.get().getClass().getName() );
System.out.println();
System.out.println("b data : "+b.get());
//반환된 변수 타입 출력
System.out.println("b E type : "+b.get().getClass().getName() );
}
}
------------------------------------------
(출력 결과)
a data : 10
a E Type : java.lang.String
b data : 10
b E Type : java.lnag.Integer
public <T> T genericMethod(T o){ // 제네릭 메소드
...
}
[접근 제어자] <제네릭타입> [반환타입] [메소드명]([제네릭타입] [파라미터]){
// 텍스트
}
* 클래스와는 다르게 반환 타입 이전에 <> 제네릭 타입 선언
class ClassName<E>{
private E element; // 제네릭 타입 변수
void set(E element){ // 제네릭 파라미터 메소드
this.element = element;
}
E get(){// 제네릭 타입 반환 메소드
return element;
}
<T> T genericMethod(T o){ // 제네릭 메소드
return o;
}
}
public class Main{
public static void main(String[] args) {
ClassName<String> a = new ClassValue<String>();
ClassName<Integer> b = new ClassValue<Integer>();
a.set("10");
b.set(10);
System.out.println("a data : "+a.get());
//반환된 변수 타입 출력
System.out.println("a E type : "+a.get().getClass().getName() );
System.out.println();
System.out.println("b data : "+b.get());
//반환된 변수 타입 출력
System.out.println("b E type : "+b.get().getClass().getName() );
//제네릭 메소드 Integer
System.out.println("<T> returnType : "+a.genericMethod(3).getClass().getName());
//제네릭 메소드 String
System.out.println("<T> returnType : "+a.genericMethod("ABCD").getClass().getName());
//제네릭 메소드 ClassName b
System.out.println("<T> returnType : "+a.genericMethod(b).getClass().getName());
}
}
------------------------------------------------
(출력)
a data : 10
a E Type : java.lang.String
b data : 10
b E Type : java.lang.Integer
<T> returnType : java.lang.Integer
<T> returnType : java.lang.String
<T> returnType : ClassName
어떤 타입으로든 대체될 수 있는 타입의 파라미터
?
기호로 사용하며 일반적으로 extends
와 super
키워드 조합해 사용
<? extends T> // 상한 제한 - T와 그 이하 클래스 타입만 파라미터 가능
<? super T> // 하한 제한 - T와 그 이상 클래스 타입만 파라미터 가능