关于集合的有意义的代码 —— (一)
程序员文章站
2022-06-07 12:28:19
...
今天的代码主要是对集合中排序功能的体现,集合中排序有客户化排序和自然排序,两种都有体现。
package csdn;
import java.util.Comparator;
public class Student implements Comparable{
private int id;
private String name;
private int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = 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;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
@Override
public int compareTo(Student s) {
if(this.name.equals("tom") && s.name.equals("tom")){
return -1;
}else if (!this.name.equals("tom") && s.name.equals("tom")) {
return 1;
}else {
return this.score - s.score;
}
}
}
//class MyComparator implements Comparator {
//
// public int compare(Student o1, Student o2) {
// if(o1.getName()=="tom"&&o2.getName()!="tom"){
// return -1;
// }else if(o1.getName()!="tom"&&o2.getName()=="tom"){
// return 1;
// }else{
// if(o1.getScore()>o2.getScore()){
// return -1;
// }else if(o1.getScore() set = new TreeSet();
Student s1 = new Student(1, "zmy", 88);
Student s2 = new Student(2, "mary", 86);
Student s3 = new Student(3, "tom", 60);
Student s4 = new Student(4, "lil", 59);
Student s5 = new Student(5, "lily", 95);
Student s6 = new Student(6, "tom", 70);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
set.add(s6);
Iterator it = set.iterator();
while (it.hasNext()) {
Student student = (Student) it.next();
System.out.println(student);
}
}
}
上一篇: jquery datepicker 日期中文化时,年和月显示在两行
下一篇: 第二章 有意义的命名