import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.TreeSet; public class SortListDemos { public static void main(String[] args) { // //linkhashsetdemos(); //treesetdemos(); treesetStudentdemos(); } private static void treesetStudentdemos() { // 储存学生对象,依据其年龄排序,如果年龄下同,再比较其姓名 TreeSet ts = new TreeSet(); ts.add(new MinStudent("ccc",22)); ts.add(new MinStudent("ddd",22)); ts.add(new MinStudent("aaa",21)); ts.add(new MinStudent("dad",23)); ts.add(new MinStudent("fff",25)); ts.add(new MinStudent("sss",22)); ts.add(new MinStudent("jjj",20)); Iterator it = ts.iterator(); while(it.hasNext()) { MinStudent ms = (MinStudent)it.next(); System.out.println(ms.toString()); } } private static void treesetdemos() { // TODO Auto-generated method stub TreeSet ts = new TreeSet(); ts.add("abd"); ts.add("kkk"); ts.add("hhg"); ts.add("eee"); ts.add("abd"); System.out.println("TreeSet :"+ts); } private static void linkhashsetdemos() { // TODO Auto-generated method stub HashSet lhs = new LinkedHashSet(); //添加元素 lhs.add("abd"); lhs.add("kkk"); lhs.add("hhg"); lhs.add("eee"); lhs.add("abd"); System.out.println("HashSet:"+lhs); } } class MinStudent implements Comparable { public int getName; private String name ; private int age; MinStudent(String name ,int age) { this.name = name ; this.age=age; } public int getAge() { return age; } public String getName() { return name; } public String toString() { return "name:"+name +" --- age"+age; } @Override public int compareTo(Object o) { // MinStudent s =(MinStudent) o; //先按照年龄排序 int i=this.getAge()-s.getAge(); if(i ==0) return this.getName().compareTo(s.getName()); return i; } }
黑马程序员——java——TreeSet集合中储存学生对象,按照其年龄进行排序
原文地址:http://blog.csdn.net/zl18603543572/article/details/46558809