public class GenericDemo {
public static void main(String[] args) {
Collection collection =new ArrayList();
//添加元素
collection.add("java");
collection.add(12);
System.out.println("-----------------");
System.out.println(collection);
for (Object o: collection) {
System.out.println(o);
}
System.out.println("--------------------");
Iterator iterator=collection.iterator();
while (iterator.hasNext()){
Object next = iterator.next();
System.out.println(next);
}
}
}
这是没有使用泛型的情况,可以发现任何对象都可以装进去,但是一旦我们修改为
Collectioncollection =new ArrayList();
就表示只能接收String对象,而不是所有都能装进去(12就不能装进去,会报错)
泛型类public class Generic{ private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } }
//测试类
public class GenericDemo {
public static void main(String[] args) {
Generic g1=new Generic<>();
g1.setT("王五");
System.out.println(g1.getT());
Generic g2=new Generic<>();
g2.setT(12);
System.out.println(g2.getT());
}
}
泛型方法
public class Generic{ public void show(T t){ System.out.println(t); } }
//测试类
public class GenericDemo {
public static void main(String[] args) {
Generic generic=new Generic<>();
generic.show("zhangsan");
Generic generic1=new Generic<>();
generic1.show(12);
}
}
//public class Generic{ // public void show(T t){ // System.out.println(t); // } //} public class Generic { public void show(T t){ System.out.println(t); } }
//测试类
public class GenericDemo {
public static void main(String[] args) {
Generic generic=new Generic();
generic.show("zhangsan");
generic.show(15);
}
}
泛型接口
public interface Generic{ void show(T t); }
public class GenericImplimplements Generic { @Override public void show(T t) { System.out.println(t); } }
public class test {
public static void main(String[] args) {
GenericImpl generic=new GenericImpl();
generic.show("wangwu");
Generic generic1=new GenericImpl<>();
generic1.show(12);
}
}
类型通配符
public class GenericDemo {
public static void main(String[] args) {
//类型通配符:?
List> list=new ArrayList
可变参数
public class test2 {
public static void main(String[] args) {
System.out.println(sum(10, 20, 30));
System.out.println(sum(10, 20, 30,40));
System.out.println(sum(10, 20, 30,50));
}
public static int sum(int... a){
int num=0;
for (Integer i: a){
num+=i;
}
return num;
}
}
可变参数的使用



