泛型类和泛型接口
package com.yuzhenc.collection;
public class Test06 {
public static void main(String[] args) {
Person<String,Integer,Integer> p1 = new Person<>("sqlboy",25,1);
Person<String,Integer,String> p2 = new Person<>("sqlgirl",25,"男");
Person p3 = new Person<String,Integer,Integer>("sqlboy",25,1);
Person p4 = new Person<String,Integer,String>("sqlgirl",25,"男");
p3 = p4;
Person p5 = new Person(1,2,true);
}
}
class Person <A,B,C> {
A name;
B age;
C sex;
public Person() {}
public Person(A name, B age, C sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public A getName() {
return name;
}
public void setName(A name) {
this.name = name;
}
public B getAge() {
return age;
}
public void setAge(B age) {
this.age = age;
}
public C getSex() {
return sex;
}
public void setSex(C sex) {
this.sex = sex;
}
}
class Student extends Person <String,Integer,String> {
}
class Teacher<A,B,C> extends Person<A,B,C> {
public Teacher() {}
public Teacher(A name, B age, C sex) {
super(name, age, sex);
}
public void c() {
C[] c = (C[])new Object[10];
}
}
泛型方法
package com.yuzhenc.collection;
public class Test07 {
public static void main(String[] args) {
System.out.println(a(true));
System.out.println(a(1));
System.out.println(a("sqlboy"));
System.out.println(a(1.1));
}
public static <T> T a(T t) {
return t;
}
}
通配符
package com.yuzhenc.collection;
import java.util.ArrayList;
import java.util.List;
public class Test08 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("sqlboy");
list.add("Hello");
b(list);
}
public static void a(List<String> a) {
for (String s : a) {
System.out.println(s);
}
}
public static void b(List<?> b) {
for (Object s : b) {
System.out.println(s);
}
b.add(null);
Object o1 = b.get(0);
Object o2 = b.get(1);
Object o3 = b.get(2);
System.out.println(o1);
System.out.println(o2);
System.out.println(o3);
}
}
泛型受限
package com.yuzhenc.collection;
import java.util.ArrayList;
import java.util.List;
public class Test09 {
public static void main(String[] args) {
List<Object> a = new ArrayList<>();
List<Person> b = new ArrayList<>();
List<Student> c = new ArrayList<>();
List<? extends Person> list1 = null;
list1 = b;
list1 = c;
List<? super Person> list2 = null;
list2 = a;
list2 = b;
}
}
|