TreeSet,Comparator集合应用

--

package com.sdtu.cn;

import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;
class  Student{
  String name;
  int age;
  float score;
 public Student(String name, int age, float score) {
  super();
  this.name = name;
  this.age = age;
  this.score = score;
 }
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public float getScore() {
  return score;
 }

 public void setScore(float score) {
  this.score = score;
 }

 @Override
 public String toString() {
  return "Student [name=" + name + ", age=" + age + ", score=" + score
    + "]";
 }
  static class StudentCompare implements Comparator {

  @Override
  public int compare(Object o1, Object o2) {
   Student s1 = (Student) o1;
   Student s2 = (Student) o2;
   int result = s1.score> s2.score?1:(s1.score==s2.score?0:-1);
   if(result == 0){
    result = s1.name.compareTo(s2.name);
   }
   return result;
  }
  
  }
 
}
public class TreeSetTest {
 public static void main(String[]args){
 TreeSet ts = new TreeSet(new Student.StudentCompare());
 ts.add(new Student("老五",21,90));
 ts.add(new Student("老二",23,79));
 ts.add(new Student("老四",24,71));
 ts.add(new Student("老三",23,75));
 ts.add(new Student("老大",25,78));
 Iterator it = ts.iterator();
 while(it.hasNext()){
  System.out.println(it.next());
 }
 }
}

 

 

第二种情况(参考网络)

 

import java.util.Iterator;
import java.util. * ;

public class TreeSetTest {
public static void main(String[] args) {
Set ts
= new TreeSet();
ts.add(
new Teacher( " zhangsan " , 1 ));
ts.add(
new Teacher( " lisi " , 2 ));
ts.add(
new Teacher( " wangmazi " , 3 ));
ts.add(
new Teacher( " mazi " , 3 ));
Iterator it
= ts.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}


class Teacher implements Comparable {
int num;
String name;

Teacher(String name,
int num) {
this .num = num;
this .name = name;
}

public String toString() {
return " 学好 " + num + " 姓名 " + name;
}

public int compareTo(Object o) {
Teacher ss
= (Teacher) o;
int result = num > ss.num ? 1 : (num == ss.num ? 0 : - 1 );
if (result == 0 ) {
result
= name.compareTo(ss.name);
}
return result;
}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值