Java set重写排序

关于Comparator方法如何理解排序
① jdk官方默认是升序,是基于:

< return -1
= return 0
>  return 1

如果要想
package SetTest;

import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeSet;

public class SetTest {
public static void main(String[] args) {
TreeSet tree = new TreeSet(new MyComparator());
// tree.add(1);
// tree.add(2);
// tree.add(6);
// tree.add(9);
tree.add(new Student(“tom”,19,89));
tree.add(new Student(“sunny”,29,85));
tree.add(new Student(“jack”,23,56));
tree.add(new Student(“rose”,18,66));
Iterator it = tree.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Student{
String name;
int age;
double score;

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

public Student(String name, int age, double score) {
	super();
	this.name = name;
	this.age = age;
	this.score = score;
}

}
class MyComparator implements Comparator{
//0:相同 负数:小于 正数:大于
@Override
public int compare(Object arg0, Object arg1) {
Student stu1 = (Student)arg0;
Student stu2 = (Student)arg1;
if(stu1.score<stu2.score)
return 1;
else
return -1;
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值