关于集合的有意义的代码 —— (一)

来源:互联网 发布:windows平板镜像下载 编辑:程序博客网 时间:2024/06/06 00: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;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";}@Overridepublic 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);}}}

原创粉丝点击