❗️제네릭이 뭔지 궁금하다면 이전 포스트를 참고하길 바란다.
https://suhyeon-developer.tistory.com/23
[JAVA] Generic 한 걸음 나아가기! (1) 개념편
제네릭(Generic)이란? ❗️ Java로 개발하면서 한 번쯤 List 또는 Map 같이 기호 안에 타입이 적혀져있는 것을 경험 해봤을 것이다. 이게 뭘까? ✅ 제네릭이 뭐야? "Java 프로그래밍 언어에서 사용되는
suhyeon-developer.tistory.com
메서드(method)에 제네릭 적용
public class Generics {
static <T> void print(T t) {
System.out.println(t.toString());
}
}
✅ static <T> : <T>는 제네릭 타입 매개변수를 나타낸다. 여기서<T>는 임의의 타입을 의미하며, 실제 사용될 때 어떤 타입으로 대체될지를 나타낸다.
✅ print(T t) : 메서드의 이름은 print 이며, 매개변수로 제네릭 타입 T인 t 를 받는다.
static 사용 가능
❓그렇다면 아래 예제는 될까?
public class Generics<T> {
static <T> void print(T t) {
System.out.println(t.toString());
}
}
정답은 ❌
틀린 이유는 static 때문이다. 위 코드처럼 class 레벨에 제네릭을 사용하면 static 사용이 안된다.
✅ T라는 타입 변수는 클래스의 인스턴스가 만들어질 때 타입 인자를 받아오게 되어있는데 static은 클래스의 인스턴스를 만들지 않고 사용하기 때문에 T를 알 방법이 없다.
따라서 static을 사용하고 싶다면 method 레벨에 제네릭 사용하면 된다.
생성자(constructor)에서 제네릭 사용
public class Generics {
public <S> Generics(S s) {
}
}
제한된 제네릭 (bounded type parameter)
public class Generics {
static <T extends List> void print(T t) {}
// bounded type parameter 응용
// Comparable 인터페이스를 구현한 클래스만 사용 가능
static <T extends Comparable<T>> long countGreaterThan(T[] arr, T elem) {
return Arrays.stream(arr).filter(s -> s.compareTo(elem) > 0).count();
}
public static void main(String[] args) {
// Integer 배열에 대해 countGreaterThan 메서드 호출
Integer[] arr1 = new Integer[]{1, 2, 3, 4, 5};
System.out.println(countGreaterThan(arr1, 4)); // arr1에 대해 4보다 큰 값의 개수 출력
// String 배열에 대해 countGreaterThan 메서드 호출
String[] arr2 = new String[]{"a", "b", "c", "d", "e"};
System.out.println(countGreaterThan(arr2, "c")); // arr2에 대해 "c"보다 큰 값의 개수 출력
}
}
✅ countGreaterThan()은 Comparable 인터페이스를 구현한 클래스만을 대상으로 한다. 코드를 보면 Integer 와 String 타입을 T에 대입했는데 Integer와 String은 Comparable 인터페이스를 구현했으며 compareTo 메서드를 제공하고 있다.
✅ static <T extends Comparable<T>> long countGreaterThan(T[] arr, T elem) 이라고 사용한 경우에 T가 어떤 타입으로 한정된 것이 아니기 때문에 Integer와 String 둘다 사용이 가능하며 Comparable 인터페이스를 구현한 어떠한 클래스는 다 countCreaterThan 메서드를 사용할 수 있습니다.
🔆 해당 글은 '토비의 스프링' Youtube를 참고하여 공부한 후 작성한 글입니다.
'BE > Java' 카테고리의 다른 글
[JAVA] ConcurrentHashMap은 뭘까? (synchronizedMap, HashMap과의 비교) (0) | 2024.06.03 |
---|---|
[JAVA] HashMap과 HashTable의 차이 (1) | 2024.06.03 |
[JAVA] 자바 intersection type이 뭔지 알아보자! (with 람다) (0) | 2023.12.26 |
[JAVA] Generic 한 걸음 나아가기! (1) 개념편 (1) | 2023.12.23 |