TreeSet

xiaoxiao2021-02-28  31

TreeSet集合底层是二叉树数据结构,本身具有比较性,要实现Comparable接口  重写compareTo方法

import java.util.*; /* TreeSet是有序的 在存入对象的过程中,要定义按照什么来排序 存入的类要实现一个Comparable接口 方法compareTo 大于 返回正数 小于 返回负数 等于 返回零 */ public class Demo { public static void main(String[] args) { TreeSet ts= new TreeSet(); ts.add(new Person("hk3",13)); ts.add(new Person("hk1",11)); ts.add(new Person("hk2",12)); ts.add(new Person("hk4",12)); ts.add(new Person("hk0",10)); Iterator it=ts.iterator(); while(it.hasNext()) { Person p=(Person)it.next(); sop(p.getName()+" "+p.getAge()); } } public static void sop(Object obj) { System.out.println(obj); } } class Person implements Comparable //比较性 { private String name; private int age; Person(String name,int age) { this.name=name; this.age=age; } public void setName(String name) { this.name=name; } public String getName() { return name; } public void setAge(int age) { this.age=age; } public int getAge() { return age; } public int compareTo(Object obj) //这里!!!这里这里!! { if(!(obj instanceof Person)) throw new RuntimeException("shaazhes"); Person p=(Person)obj; System.out.println(this.age+"-----"+p.age); //比较过程 if(this.age>p.age) return 1; if(this.age==p.age) { return this.name.compareTo(p.name); //当年龄一样时 再比较一次姓名 } return -1; } }

转载请注明原文地址: https://www.6miu.com/read-2000024.html

最新回复(0)