Discuss / Java / Map<自定义类,v>=new TreeMap(), 自定义类自定义compareTo方法排序

Map<自定义类,v>=new TreeMap(), 自定义类自定义compareTo方法排序

Topic source

净净一隅

#1 Created at ... [Delete] [Delete and Lock User]

public class Student extends Person implements Comparable<Student>{

  private int score=0;

  public Student(String name,int age,int score) {

  super(name,age);

  this.score=score;

  }

  public Student(String name,int score) {

  super(name);

  this.score=score;

  }

public int getScore() {

return score;

}

public void setScore(int score) {

this.score = score;

}

public int compareTo(Student other) {

if(this.score==other.score && this.name.equals(other.getName()) && this.age==other.getAge())

{

return 0;

}

//return this.getName().compareTo(other.getName());  //姓名首字母升序排序

//return other.getName().compareTo(this.getName()); //姓名首字母降序排序

//return other.getScore()-this.getScore();  //分数降序排序

return this.getScore()>other.getScore() ? 1:-1; //分数升序排序

}

public String  toString() {

return "Student[name: "+this.name+", age:"+this.age+", score:"+this.score+"]\n";

}

public static void main(String[] args) {

Map<Student,Integer> map=new TreeMap<>();

map.put(new Student("Apple", 19,33), 1);

map.put(new Student("Orange", 19,33), 2);

map.put(new Student("Banana", 23,44), 3);

map.put(new Student("Orange", 18,33), 4);

log.info(new Student("Apple", 19,33).hashCode());  //871441287

log.info(new Student("Orange", 20,33).hashCode()); //1221078458

log.info(new Student("Apple",19,33).equals(new Student("Orange", 20,33))); //false

    log.info(map.get(new Student("Orange", 20,33)));  //null 

log.info(map.get(new Student("Apple", 19,33)));   //1

log.info(map);

/*{Student[name: Orange, age:18, score:33]=4, 

* Student[name: Orange, age:19, score:33]=2, 

* Student[name: Apple, age:19, score:33]=1, 

* Student[name: Banana, age:23, score:44]=3}

   */

}

}

净净一隅

#2 Created at ... [Delete] [Delete and Lock User]

@Override

public boolean equals(Object o) {

if(o instanceof Student) {

Student s=(Student) o;

return Objects.equals(this.name, s.getName()) && this.age==s.getAge() && this.score==s.getScore();

}

return false;

}

@Override

public int hashCode() {

return Objects.hash(this.name, this.age, this.score);

}


  • 1

Reply