package com.jdk150.bean;
import java.util.ArrayList;
import java.util.List;
public class GenericsFoo<T> {
private T foo;
public T getFoo() {
return foo;
}
public void setFoo(T foo) {
this.foo = foo;
}
public static void main(String[] args){
GenericsFoo<Integer> gfi = new GenericsFoo<Integer>();
gfi.setFoo(new Integer(123));
int i = gfi.getFoo();
GenericsFoo<String> gfs = new GenericsFoo<String>();
gfs.setFoo("hello!");
String s = gfs.getFoo();
GenericsFoo<Boolean> gfb = new GenericsFoo<Boolean>();
gfb.setFoo(false);
boolean b = gfb.getFoo();
//传统的list什么对象都能放
List list = new ArrayList();
list.add(i);
list.add(s);
list.add(b);
for(int j=0;j<list.size();j++){
System.out.println(list.get(j));
}
//泛型list只能放所定义的类型对象
List<Integer> l = new ArrayList<Integer>();
for(int k=0;k<10;k++){
l.add(k+1);
}
// l.add("hello"); //错误的添加
for(int x=0;x<l.size();x++){
System.out.println(l.get(x));
}
}
}
import java.util.ArrayList;
import java.util.List;
public class GenericsFoo<T> {
private T foo;
public T getFoo() {
return foo;
}
public void setFoo(T foo) {
this.foo = foo;
}
public static void main(String[] args){
GenericsFoo<Integer> gfi = new GenericsFoo<Integer>();
gfi.setFoo(new Integer(123));
int i = gfi.getFoo();
GenericsFoo<String> gfs = new GenericsFoo<String>();
gfs.setFoo("hello!");
String s = gfs.getFoo();
GenericsFoo<Boolean> gfb = new GenericsFoo<Boolean>();
gfb.setFoo(false);
boolean b = gfb.getFoo();
//传统的list什么对象都能放
List list = new ArrayList();
list.add(i);
list.add(s);
list.add(b);
for(int j=0;j<list.size();j++){
System.out.println(list.get(j));
}
//泛型list只能放所定义的类型对象
List<Integer> l = new ArrayList<Integer>();
for(int k=0;k<10;k++){
l.add(k+1);
}
// l.add("hello"); //错误的添加
for(int x=0;x<l.size();x++){
System.out.println(l.get(x));
}
}
}