728x90
Generic이란 클래스에 사용할 타입을 디자인시에 지정하는 것이 아니라 클래스를 사용할때 지정하는 기법이다.
<T> 는 자료형
<E> 는 객체
<K> 는 key 값
<V> 는 값을 의미한다.
<T> 는 자료형
<E> 는 객체
<K> 는 key 값
<V> 는 값을 의미한다.
5.0 이전 스타일
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
class Generic_1
{
private void testCollection()
{
List list = new ArrayList();
//객채추가
list.add(new String("Hello world"));
list.add(new String("Goodbye"));
list.add(new Integer(95));
disp(list);// 메소드 호출
}
///////////////////////////////////////////////////////////////
private void disp(Collection c)
{
Iterator iter= c.iterator();
while(iter.hasNext()) //존재하는한 계속 돌아라
{
String temp = (String)iter.next();
//Integer 타입을 String타입으로 캐스팅 해서 ClassCastException 발생
System.out.println("temp :"+temp);
}
}
////////////////////////////////////////////////////////////////
public static void main( String [] args )
{
Generic_1 g = new Generic_1();
g.testCollection();
}// end main
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
class Generic_1
{
private void testCollection()
{
List list = new ArrayList();
//객채추가
list.add(new String("Hello world"));
list.add(new String("Goodbye"));
list.add(new Integer(95));
disp(list);// 메소드 호출
}
///////////////////////////////////////////////////////////////
private void disp(Collection c)
{
Iterator iter= c.iterator();
while(iter.hasNext()) //존재하는한 계속 돌아라
{
String temp = (String)iter.next();
//Integer 타입을 String타입으로 캐스팅 해서 ClassCastException 발생
System.out.println("temp :"+temp);
}
}
////////////////////////////////////////////////////////////////
public static void main( String [] args )
{
Generic_1 g = new Generic_1();
g.testCollection();
}// end main
}
5.0 이후 스타일
class Generic<T>
{
T[] v;
//Generic 타입으로 설정
public void set(T[] n)
{
v = n;
}
// T[]의 원소 출력
public void disp()
{
for(T s:v)
{
System.out.println(s);
}
}
}
//Generic 타입 사용하기
class Generic_3
{
public static void main( String [] args )
{
Generic<String> g = new Generic<String>(); // 객체생성 String타입으로 사용하겠다.
String []str = {"신세경은 ","조낸 ","이쁘다"};
g.set(str);
g.disp();
Generic<Integer> g2 = new Generic<Integer>();//객체생성 int타입으로 사용하겠다.
Integer[] arr = {100,200,300};
g2.set(arr);
g2.disp();
Generic<Double> g3 = new Generic<Double>();
Double[] dd= {121.5,2343.3,234.45};
g3.set(dd);
g3.disp();
}// end main
}