TreeSet集合储存自定义类型元素(实现了Comparable接口)

来源:互联网 发布:暴走大事件禁播了知乎 编辑:程序博客网 时间:2024/06/13 05:44
package com.yingcheng1101.collection.set.treeset;import java.util.TreeSet;public class Set_TreeSet_2 implements Comparable {private String name;private int age;// 对象一创建就需要有年龄与姓名public Set_TreeSet_2(String name, int age) {this.name = name;this.age = age;}// 覆盖toString()public String toString() {return this.name + ":" + this.age;}public int compareTo(Object obj) {// 根据对象的年龄来排序if (!(obj instanceof Set_TreeSet_2)) {// 如果对象不是Set_TreeSet_2类的,抛出运行时异常,结束程序的运行throw new RuntimeException("类型错误");}return this.age - ((Set_TreeSet_2) obj).age;}public static void main(String[] args) {// 让元素自身具备比较的方法,需要元素是实现了Comparable()接口的类的实例TreeSet tree = new TreeSet();tree.add(new Set_TreeSet_2("ddd", 25));tree.add(new Set_TreeSet_2("ccc", 33));tree.add(new Set_TreeSet_2("a", 19));tree.add(new Set_TreeSet_2("bb", 21));System.out.println(tree);}}// [a:19, bb:21, ddd:25, ccc:33]

阅读全文
0 0
原创粉丝点击