public class Mydemo1 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("asd");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
Object s = iterator.next();
String str = (String) s;//需要转换类型
System.out.println(str);
}
while (iterator.hasNext()) {
String s = iterator.next();//直接转换为定义类型,无需转换类型
System.out.println(s);
}
}
}
2.泛型类
public class Mydemo2<T, M> {
private T t;
private M m;
public Mydemo2() {
}
public Mydemo2(T t, M m) {
this.t = t;
this.m = m;
}
public T getT() {
return t;
}
public M getM() {
return m;
}
}
public class TestDemo2 {
public static void main(String[] args) {
Mydemo2<String, Integer> mydemo2 = new Mydemo2<String, Integer>("字符串",123);
System.out.println(mydemo2.getT()+"and"+mydemo2.getM());//输出: 字符串and123
}
}
3.泛型接口
public interface Myinterface<M> {
void show(M m);
}
public class Myclass1 implements Myinterface<String>{
@Override
public void show(String s) {
System.out.println(s);
}
}
public class TestInterface {
public static void main(String[] args) {
Myclass1 myclass1 = new Myclass1();
myclass1.show("泛型接口");//输出: 泛型接口
}
}
4.泛型方法
public class Myclass1 {
public<T> void show(T t){
System.out.println(t);
}
}
public class Test {
public static void main(String[] args) {
Myclass1 myclass1 = new Myclass1();
myclass1.show(4);//输出: 4
}
}
5.泛型通配符
public class Person {
}
public class Student extends Person{
}
public class Teacher extends Person{
}
public class Test {
public static void main(String[] args) {
ArrayList<?> list = new ArrayList<Person>();
ArrayList<?> list1 = new ArrayList<Student>();
ArrayList<?> list2 = new ArrayList<Teacher>();
ArrayList<? extends Person> list3 = new ArrayList<Person>();//?只能是Person或者Person的子类
ArrayList<? extends Person> list4 = new ArrayList<Student>();
ArrayList<? extends Person> list5 = new ArrayList<Teacher>();
//ArrayList<?extends Person> list6 = new ArrayList<Object>();//报错
ArrayList<? super Person> list7 = new ArrayList<Person>();//?只能是Person或者Person的父类
ArrayList<? super Person> list8 = new ArrayList<Object>();
//ArrayList<? super Person> list9 = new ArrayList<Student>();//报错
//ArrayList<? super Person> list10 = new ArrayList<Teacher>();//报错
}
}