Generics ex 02
import java.util.*;
public class TypeTest {
public static void main(String[] args){
//Class Vector<E>
Vector<String> v1 = new Vector<String>();
// add(E e)
v1.add("1");
v1.add("2");
Vector<String> v2 = new Vector<String>();
v2.add("3");
v2.add("4");
// addAll(Collection<? extends E> c)
v1.addAll(v2);
// Vector(Collection<? extends E> c)
ArrayList<String> al = new ArrayList<String>();
al.add("Hello");
Vector<Object> v3 = new Vector<Object>(al);
// Class Class<T>
// Type Parameters:
// T - the type of the class modeled by this Class object.
// For example, the type of String.class is Class<String>.
// Use Class<?> if the class being modeled is unknown.
Class<String> c = String.class;
}
}
package generics;
import java.util.ArrayList;
/* ShoppingCart라는 클래스는 내부의 데이터가 일반화 된 상태이다. 즉, 선언시에 바로자료형이 결정되는 것이
* 아니라 이 클래스를 사용할 때 자료형이 결정된다는 의미이다. 그러므로 이 클래스를 사용할 때는
* 내부의 자료형을 반드시 정의해 주어야 한다.
* 일반화(Generics)를 적용한 클래스를 선언하고 사용하는 예
*/
class ShoppingCart<T> {
ArrayList<T> al = new ArrayList<T>();
void add(T goods){
al.add(goods);
}
ArrayList<T> getGoods(){
return al;
}
}
public class GenericsDemo {
public static void main(String[] args) {
ShoppingCart<String> cart = new ShoppingCart<String>();
cart.add("PMP");
cart.add("MP3");
ArrayList<String> al = cart.getGoods();
for(int i=0;i<al.size();i++){
System.out.println(i+". "+al.get(i));
}
}
}