通配符:表示当前类型可以是任何类型
它也会进行类型擦除的 擦除到Object
Object ArrayList
Number ArrayList
Integer ArrayList
库的开发 :
写一个函数,打印容器内的元素 ArrayList:容器
class GenericList{
//泛型写:
public static<T> void printList1(ArrayList<T> list){
for(T obj : list){
System.out.print(obj+" ");
}
System.out.println();
}
public static<T> void printList2(ArrayList<Object> list){
for(Object obj : list){
System.out.print(obj+" ");
}
System.out.println();
}
public static<T> void printList(ArrayList<?> list){
for(Object obj : list){
System.out.print(obj+" ");
}
System.out.println();
}
}
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
GenericList.printList(list);
//ArrayList<Object> obj = new ArrayList<Integer>();
//obj[0] = 10; obj[1] = "梨";
}
}
通配符既有上界,又有下界
通配符的下界: ? super T
通配符的上界: ? extends T
class GenericAlg3{
//泛型实现
public static<T extends Comparable<T>> T findMaxPerson1(ArrayList<T> list){
T maxPerson = list.get(0);
for(int i = 1;i < list.size();i++){
if(maxPerson.compareTo(list.get(i)) < 0){
maxPerson = list.get(i);
}
}
return maxPerson;
}
//下界 =====》
//? super T 找到是否有T类型的基类实现了Comparable接口
public static<T extends Comparable<? super T>> T findMaxPerson(ArrayList<T> list){
T maxPerson = list.get(0);
for(int i = 1;i < list.size();i++){
if(maxPerson.compareTo(list.get(i)) < 0){
maxPerson = list.get(i);
}
}
return maxPerson;
}
}
class Person implements Comparable<Person>{
private String name;
public Person(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
@Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return name.compareTo(o.name);
}
}
class Student extends Person{
private int age;
public Student(String name, int age) {
super(name);
this.age = age;
}
@Override
public String toString() {
return "Student [age=" + age + "]";
}
}
public class TestDemo1 {
public static void main3(String[] args) {
ArrayList<? extends Person> list = new ArrayList<Student>();
//上界用来读取的(查一下)
}
public static void main2(String[] args) {
ArrayList<Student> list1 = new ArrayList<Student>();
list1.add(new Student("wang",10));
list1.add(new Student("gao",20));
list1.add(new Student("a",30));
System.out.println(GenericAlg3.findMaxPerson(list1));
//汉字比较??????????????
}
public static void main(String[] args) {
ArrayList<Person> list1 = new ArrayList<Person>();
list1.add(new Person("wang"));
list1.add(new Person("gao"));
list1.add(new Person("abcd"));
System.out.println(GenericAlg3.findMaxPerson(list1));
}
}