/*
泛型:指定集合类型,在运行而不是编译时时就发现问题,消除安全隐患。避免强转。
*/
package pack;
import java.util.ArrayList;
import java.util.Iterator;
/*public class Main {
public static void sys(Object obj) {
System.out.println(obj);
}
public static void main(String[] args) {
TreeSet<String> al = new TreeSet<String>(new MyComparator()); //集合泛型
al.add("aa");
al.add("bbb");
al.add("c");
Iterator<String> it = al.iterator();
while(it.hasNext()) {
String s = (String)it.next(); //避免强转
sys(s);
sys(it.next());
}
}
}
class MyComparator implements Comparator<String> {
public int compare(String o1,String o2) {
int a = new Integer(o2.length()).compareTo(new Integer(o1.length()));
if(a==0) {
return o2.compareTo(o1);
}
return a;
}
}*/
/*public class Main {
public static void main(String[] args) {
Demo<Integer> d = new Demo<Integer>();
d.show(4);
d.show(new Integer(5));
Demo<String> d1 = new Demo<String>();
d1.show("haha");
}
}
class Demo<T> { //泛型方法,当前不知定义什么类型
public void show(T t) {
System.out.println(t);
}
}
*/
/*interface Inter<T> { //泛型接口
void show(T t);
}
class Demo<T> implements Inter<T> {
public void show(T t) {
System.out.println(t);
}
}
public class Main {
public static void main(String[] args) {
Demo<Integer> d = new Demo<Integer>();
d.show(new Integer(3));
}
}
*/
public class Main {
public static void main(String[] args) {
ArrayList<String> al1 = new ArrayList<String>();
al1.add("java1");
al1.add("java2");
al1.add("java3");
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(1);
al2.add(2);
al2.add(3);
show(al1);
show(al2);
}
public static <T> void show(ArrayList<T> a) { //T可以用?代替
Iterator<T> it = a.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
原文地址:http://blog.csdn.net/sjtu_chenchen/article/details/45225699