黑马程序员技术交流社区

标题: JAVA TreeSet添加对象有问题 [打印本页]

作者: 〃Mr.Zぐ    时间: 2013-4-19 14:22
标题: JAVA TreeSet添加对象有问题
public class px {
Random rd;
TreeSet ts;
TreeSet ts1;
TreeSet ts2;
TreeSet ts3;
TreeSet ts4;
px(){
  rd=new Random();
  //ts=new TreeSet();
  
  ts=new TreeSet(new Comparator(){

   public int compare(Object o1, Object o2) {
    player p1=(player)o1;
    player p2=(player)o2;
    return p1.whole<p2.whole?1:p1.whole<p2.whole?-1:0;
   }
   
  });
  
  ts1=new TreeSet(new Comparator(){

   public int compare(Object o1, Object o2) {
    player p1=(player)o1;
    player p2=(player)o2;
    return p1.money<p2.money?1:p1.money<p2.money?-1:0;
   }
   
  });
  
  ts2=new TreeSet(new Comparator(){

   public int compare(Object o1, Object o2) {
    player p1=(player)o1;
    player p2=(player)o2;
    return p1.wood<p2.wood?1:p1.wood<p2.wood?-1:0;
   }
   
  });
  
  ts3=new TreeSet(new Comparator(){

   public int compare(Object o1, Object o2) {
    player p1=(player)o1;
    player p2=(player)o2;
    return p1.sin<p2.sin?1:p1.sin<p2.sin?-1:0;
   }
   
  });
  
  ts4=new TreeSet(new Comparator(){

   public int compare(Object o1, Object o2) {
    player p1=(player)o1;
    player p2=(player)o2;
    return p1.death<p2.death?1:p1.death<p2.death?-1:0;
   }
   
  });
}

public void generate(){
  for(int i=0;i<5;i++){
   player p=new player(rd.nextInt(100),rd.nextInt(100),rd.nextInt(100),rd.nextInt(100));
   add(p);
  }
}
public void add(player p){
  ts.add(p);
  ts1.add(p);
  ts2.add(p);
  ts3.add(p);
  ts4.add(p);
}
public void show(TreeSet ts){
  System.out.println(ts.size());
  Iterator it=ts.iterator();
  while(it.hasNext()){
   ((player)it.next()).show();
  }
  System.out.println();
}
public static void main(String[] args) {
  px p=new px();
  p.generate();
  p.show(p.ts);
}
}
class player/* implements Comparator*/{
int money;
int wood;
int sin;
int death;
int whole;
player(int money,int wood,int sin,int death){
  this.money=money;
  this.wood=wood;
  this.sin=sin;
  this.death=death;
  whole=money+wood+sin+death;
}
public void show(){
  System.out.print("金币:"+money+'\t');
  System.out.print("木材:"+wood+'\t');
  System.out.print("罪恶值:"+sin+'\t');
  System.out.print("死亡数:"+death+'\t');
  System.out.println("总分:"+whole);
}
/*public int compare(Object o1, Object o2) {
  player p1=(player)o1;
  player p2=(player)o2;
  return p1.whole<p2.whole?1:p1.whole<p2.whole?-1:0;
}*/
}
为什么我生成的对象没有全部被添加进去?而且ts,ts1,ts2,ts3,ts4每个Set里保存对象的数量都不一定。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2