일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- sql
- 테이블
- CSS
- 공부를열심히
- 객체지향프로그래밍
- javascript
- 주말이다..
- jsp
- 코딩
- 공부
- DB
- ERWin
- Oracle
- 프로젝트
- 프로그래밍
- 객제지향프로그래밍
- Java
- 객체지향
- squery
- 데이터베이스
- 웹
- UI
- 객제지향
- Project
- web
- 웹프로그래밍
- orcle
- html
- 자바
- 오라클
Archives
- Today
- Total
햄찌개
JAVA - Generic 메서드 본문
* 재너릭 메서드 <T,R> R method(T t)
*
* 파라미터 타입과 리턴타입으로 타입 파라미터를 가지는 메서드
* 선언방법 : 리턴타입앞에 <> 기호를 추가하고 타입 파라미터를 기술 후 사용함.
class Util {
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
boolean keyCompare = p1.getKey().equals(p2.getKey());
boolean valueCompare = p1.getValue().equals(p2.getValue());
return keyCompare && valueCompare;
}
}
/**
*
* 멀티타입 <K,V> 가지는 제너릭 클래스
*
* @param <K>
* @param <V>
*/
class Pair<K, V> {
private K Key;
private V value;
public Pair(K key, V value) {
super();
Key = key;
this.value = value;
}
public K getKey() {
return Key;
}
public void setKey(K key) {
Key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
//키와 값을 출력하는 메서드
public <K,V> void displayAll(K key, V value) {
System.out.println(key.toString()+" : " +value);
}
}
public class T03_GenericMethodTest {
public static void main(String[] args) {
Pair<Integer,String> p1 = new Pair<Integer,String>(1,"홍길동");
Pair<Integer,String> p2 = new Pair<Integer,String>(1,"홍길동");
//구체적 타입을 명시적을 지정
boolean result1 = Util.<Integer,String>compare(p1, p2);
if(result1) {
System.out.println("논리적(의미)으로 동일한 객체임");
}else {
System.out.println("논리적(의미)으로 동일한 객체아님");
}
Pair<String,String> p3 = new Pair<String,String>("001", "홍길동");
Pair<String,String> p4 = new Pair<String,String>("002", "홍길동");
boolean result2 = Util.<String,String>compare(p3, p4);
if(result2) {
System.out.println("논리적(의미)으로 동일한 객체임");
}else {
System.out.println("논리적(의미)으로 동일한 객체아님");
}
//제너릭 메서드 호출
p1.<String,Integer> displayAll("키값", 1234);
}
}
class Util2{
public static <T extends Number> int compare(T t1, T t2) {
double v1 = t1.doubleValue();
double v2 = t2.doubleValue();
return Double.compare(v1, v2);
}
}
/**
* 제한된 타입 파라미터(Bounded Type parameter)예제
*
*/
public class T04_GenericMethod {
public static void main(String[] args) {
int result1 = Util2.compare(10, 20);//AutoBoxing(Integer)
System.out.println(result1);
int result2 = Util2.compare(3.14, 3);
System.out.println(result2);
//Util2.compare("C", "JAVA");
}
}
'고급 JAVA' 카테고리의 다른 글
JAVA - Generic 와일드 카드 예제 - 수강 등록 (0) | 2020.09.18 |
---|---|
JAVA - Generic 와일드 카드 (0) | 2020.09.17 |
JAVA 가변형 인수 (0) | 2020.09.17 |
Java CollectionFramework - Properties를 이용하여 File처리 (0) | 2020.09.17 |
Java CollectionFramework - Map을 이용하여 전화번호 관리 예제 (0) | 2020.09.17 |