- package cn.javastudy.p6.generic.demo;
- import java.util.*;
- public class Generic {
- public static void main(String[] args)
- {
- MyTreeSet<Person> p=new MyTreeSet<Person>(new GenericDemo<Person>(){
- @Override
- public int compar(Person e1, Person e2) {
- int temp=e1.getName().compareTo(e2.getName());
- return temp==0?e1.getOld()-e2.getOld():temp;
- }});
- p.add(new Person("a张三",30));
- p.add(new Person("c李四",10));
- p.add(new Person("f王五",80));
- p.add(new Person("d赵六",25));
- p.add(new Person("e刘七",60));
- p.add(new Student("g小明同学",12));
- p.add(new Student("h小张同学",15));
- p.add(new Student("s小杨同学",8));
- p.add(new Student("z小金同学",13));
- Iterator<Person> ip=p.getIterator();
- while(ip.hasNext())
- {
- Person p1=ip.next();
- System.out.println(p1.getName()+" -"+p1.getOld());
- }
- }
- }
- interface GenericDemo<E>
- {
- public int compar(E e1,E e2);
- }
- class MyTreeSet<E>
- {
- LinkedList<E> t=new LinkedList<E>();
- GenericDemo<? super E> comparator=null;
- public MyTreeSet(GenericDemo<? super E> com)
- {
- this.comparator=com;
- }
- public void add(E e)
- {
- if(t.size()>0)
- {
- for(int i=0;i<t.size();i++)
- {
- int temp=comparator.compar(e, t.get(i));
- if(temp<0)
- {
- t.add(i,e);
- return;
- }
- }
- t.add(e);
- }
- else
- {
- t.add(e);
- }
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return t.toString();
- }
- public Iterator<E> getIterator()
- {
- return t.iterator();
- }
- }
- class Person
- {
- String name=null;
- int old=0;
- public Person(String name, int old) {
- super();
- this.name = name;
- this.old = old;
- }
- public String getName() {
- return name;
- }
- public int getOld() {
- return old;
- }
- }
- class Student extends Person
- {
- public Student(String name, int old) {
- super(name, old);
- // TODO Auto-generated constructor stub
- }
-
- }
复制代码 学习泛型之后,模拟出业的TreeeSet |