日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

TreeSet集合排序方式一:自然排序Comparable

發(fā)布時(shí)間:2025/3/20 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TreeSet集合排序方式一:自然排序Comparable 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

TreeSet集合默認(rèn)會(huì)進(jìn)行排序。因此必須有排序,如果沒有就會(huì)報(bào)類型轉(zhuǎn)換異常。

自然排序

Person class—>實(shí)現(xiàn)Comparable,實(shí)現(xiàn)compareTo()方法

package Homework1and2;import java.text.CollationKey; import java.text.Collator;/*** Person類 有屬性 name,age,sex 排序規(guī)則: 第一條件 年齡降序,第二條件 姓名 降序,第三條件 性別升序* @author Administrator**/ public class Person implements Comparable<Person> {private static String name;private int age;private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";}public Person(String name, int age, String sex) {super();this.name = name;this.age = age;this.sex = sex;}public Person() {super();}//排序規(guī)則: 第一條件 年齡降序,第二條件 姓名 降序,第三條件 性別升序@Overridepublic int compareTo(Person o) {if(age>o.age){return -1;}else if(age<o.age){return 1;}else {CollationKey key1=Collator.getInstance().getCollationKey(name);CollationKey key2=Collator.getInstance().getCollationKey(o.name);int num=key1.compareTo(key2);if(num>0){return -1;}else if(num<0){return 1;}else {CollationKey key3=Collator.getInstance().getCollationKey(sex);CollationKey key4=Collator.getInstance().getCollationKey(o.sex);int s=key3.compareTo(key4);if(s>0){return 1;}else if(s<0){return -1;}else {return 0;}}}}}

測(cè)試

public class Test1 {public static void main(String[] args){TreeSet<Person> list=new TreeSet<>();//年齡降序list.add(new Person("李白1", 15, "男"));list.add(new Person("李白2", 18, "男"));//姓名降序list.add(new Person("a妲己3", 20, "女"));list.add(new Person("z褒姒4", 20, "女"));//性別升序list.add(new Person("妲己", 17, "a女"));list.add(new Person("妲己", 17, "z男"));System.out.println(list);} }

總結(jié)

以上是生活随笔為你收集整理的TreeSet集合排序方式一:自然排序Comparable的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。