教育路上
摘要:treeset集合例子,根据年龄排序。以下是我们为大家整理的,相信大家阅读完后肯定有了自己的选择吧。
2022-03-05 16:05万睿
三、定义一个模型类,包含年龄和姓名
1、定义treeset集合存入多个模型类的对象
2、定义CompartTo方法
3、根据年龄大小排序
4、如果年龄相同再通过姓名字符串长度排序,s .lenth()
参考教材233页、234页
package mpy; import java.util.HashSet; import java.util.Objects; class Student { private String name; private int xuehao; public Student() { } public Student(String name, int xuehao) { this.name = name; this.xuehao = xuehao; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return xuehao; } public void setAge(int xuehao) { this.xuehao = xuehao; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return xuehao == student.xuehao && Objects.equals(name, student.name); } public int hashCode() { return Objects.hash(name, xuehao); } } public class HashSetDemo { public static void main(String[] args) { HashSet<Student> hs = new HashSet<>(); Student s1 = new Student("lisi", 23); Student s2 = new Student("wanger", 22); Student s3 = new Student("xiaoming", 21); Student s4 = new Student("lisi", 23); hs.add(s1); hs.add(s2); hs.add(s3); hs.add(s4); for (Student s : hs) { System.out.println(s.getName() + "," + s.getAge()); } } }
访客的评论 2023/12/03 06:21
文中描述的是准确的吗,如何报名!