修改代码使其按照姓名首字母数字排序import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; public class sort_student { public static void main(String[] args) { //创建 TreeSet 对象时指定排序器 Comparator TreeSet<student> s = new TreeSet<>(new Comparator<student>() { public int compare(student o1, student o2) { return o1.getAge() - o2.getAge(); } }); // 按照年龄插入数据 s.add(new student("Tom", 18)); s.add(new student("Bob", 14)); s.add(new student("Jack", 16)); s.add(new student("Alice", 13)); s.add(new student("Koltin", 22)); s.add(new student("Abuton", 19)); // 迭代 TreeSet 集合,按照年龄从小到大输出学生信息 Iterator<student> it = s.iterator(); while (it.hasNext()) { student tt = it.next(); sop(tt.getName() + "," + tt.getAge()); } } public static void sop(Object obj) { System.out.println(obj); } }
时间: 2023-06-23 10:08:46 浏览: 176
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class sort_student {
public static void main(String[] args) {
// 创建 TreeSet 对象时指定排序器 Comparator
TreeSet<student> s = new TreeSet<>(new Comparator<student>() {
public int compare(student o1, student o2) {
int result = o1.getName().compareTo(o2.getName());
if (result == 0) {
result = o1.getAge() - o2.getAge();
}
return result;
}
});
// 按照姓名和年龄插入数据
s.add(new student("Tom", 18));
s.add(new student("Bob", 14));
s.add(new student("Jack", 16));
s.add(new student("Alice", 13));
s.add(new student("Koltin", 22));
s.add(new student("Abuton", 19));
// 迭代 TreeSet 集合,按照姓名和年龄从小到大输出学生信息
Iterator<student> it = s.iterator();
while (it.hasNext()) {
student tt = it.next();
sop(tt.getName() + "," + tt.getAge());
}
}
public static void sop(Object obj) {
System.out.println(obj);
}
}
阅读全文