黑马程序员技术交流社区
标题:
自定义TreeSet
[打印本页]
作者:
熊永标
时间:
2013-1-10 14:46
标题:
自定义TreeSet
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
作者:
小洋人最happy
时间:
2013-1-10 14:59
不错 继续努力哈
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2