1.返回 1 那么当前的值会排在 被比较者 后面。
2.返回 0 那么当前的值【不会被加入到 TreeSet 中】,因为当前的值【被认为是跟现有的某一个值相等】。
3.返回 -1 会被添加到 被比较者 的前边。
因此:在使用 TreeSet 的时候,首先要弄明白要【按照哪一个字段进行排序】,其次如果对象【需要去重的话】要弄【明白按哪一个字段进行去重】。
例子:
- package com.dada.data;
-
-
- public class Student {
- private int id;
- private String name;
- private int score;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
-
-
- public int getScore() {
- return score;
- }
- public void setScore(int score) {
- this.score = score;
- }
- public int compareTo(Object obj) {
- int r = 0;
-
- if (obj instanceof Student) {
- Student ss = (Student) obj;
-
- if (ss.getName().equals(this.getName())) {
-
- if (ss.getScore() >= this.getScore()) {
- r = -1;
- } else {
- r = 1;
- }
- } else {
- r = 0;
- }
-
-
- } else {
- r = 0;
- }
- return r;
- }
- }