我刚编写了一段代码对几个人的名字进行比较,发现没有按照汉字拼音的顺序。
- package cn.itcast_Demo;
- import java.util.Comparator;
- import java.util.TreeSet;
- //TreeSet集合存储自定义对象并遍历(比较器接口)
- public class TreeSetTest4 {
- public static void main(String[] args) {
- //创建集合对象
- TreeSet<Student> set = new TreeSet(new Comparator<Student>(){
- @Override
- public int compare(Student s1, Student s2) {
- int a1 =s1.getName().compareTo(s2.getName());
- int a2 = a1==0?(s1.getAge()-s2.getAge()):a1;
- int a3 = a2==0?(s1.getSex().compareTo(s2.getSex())):a2;
- return a3;
- }
-
-
-
- });
- //创建自定义对象
- Student s1 = new Student("小明",14,"男");
- Student s2 = new Student("小红",12,"女");
- Student s3 = new Student("王老汉",56,"男");
- //添加对象到集合
- set.add(s1);
- set.add(s2);
- set.add(s3);
- //遍历
- for(Student s : set){
- System.out.println(s.getName()+"..."+s.getAge()+"..."+s.getSex());
-
-
- }
-
- }
-
- }
复制代码 |
|