java泛型编程 指定基类_Java 泛型高级编程 ? 类型占位符的使用 | 学步园
发布日期:2021-06-24 11:33:55 浏览次数:2 分类:技术文章

本文共 1940 字,大约阅读时间需要 6 分钟。

import java.util.*;

class Person

{

private String name;

private int age;

public Person (String name,int age)

{

this.name=name;

this.age=age;

}

public String getName()

{

return this.name;

}

public int getAge()

{

return this.age;

}

public String toString ()

{

return this.getName()+"..."+this.getAge();

}

}

class Student extends Person

{

public Student(String name,int age)

{

super(name,age);

}

public String getName()

{

return super.getName();

}

}

public class Zhanweifu {

public static void main(String args[])

{

ArrayList personlist =new ArrayList();

ArrayListstudentlist=new ArrayList();

personlist.add(new Person ("boy",20)); studentlist.add(new Student("stu-boy",20));

personlist.add(new Person ("girl",22)); studentlist.add(new Student("stu-girl",22));

personlist.add(new Person("person",30)); studentlist.add(new Student("stu-person",30));

personlist.add(new Student ("boy",20));

//print(personlist);//print(studentlist);传studentlist 将会出现编译错误

//sop(personlist);

//show(personlist);

//show(studentlist);

display(personlist);

display(studentlist);

}

public static void print(ArrayList list) //这是为ArrayList 量身定做打印,没有什么扩展性

{

for(Iterator it=list.iterator();it.hasNext();)

{

System.out.println(it.next());

}

}

public static void sop(ArrayList> list) //直接利用占位符对操作类型进行占位,对任意类型的ArrayList<> 都可以操作,原理和泛型方法差不多

{

for(Iterator>it=list.iterator();it.hasNext();)

{

System.out.println(it.next());

}

}

public static void show(ArrayList extends Person> list)//通过占位符来限制参数的类型 ,extends Person 表示 参数只能是Person 或Person 类的子类

{

for(Iterator extends Person> it=list.iterator();it.hasNext();)

{

System.out.println(it.next());

}

}

public static void display(ArrayList super Student> list)//通过占位符来限帛参数的类型,super Student 表示参数只能是Student,或Student类的父类

{

for(Iterator super Student> it=list.iterator();it.hasNext();)

{

System.out.println(it.next());

2011/10/27 20:57:44}

}

}

自然顺序进行排序。

Comparator super E> comparator)

构造一个新的空 TreeSet,它根据指定比较器进行排序。

表明在一个类体系里,排序可以共用基类的排序方法

转载地址:https://blog.csdn.net/weixin_32541333/article/details/114251475 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java数学_Java数学
下一篇:java关键字定义字符变量_JavaSE第02篇:Java基础语法之变量、数据类型

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月20日 06时48分41秒