星空网 > 软件开发 > Java

[javaSE] 集合框架(TreeSet)

TreeSet:可以对Set集合中的元素排序,默认按照ascii表排序,二叉树结构

左边叉是小的,右边叉是大的

 

存储自定义对象

定义一个类Student实现Comparable类,使自定义类具备比较性

定义属性年龄age

定义属性姓名name

实现compareTo()方法,传递进来另一个Student对象

判断当前Student对象的age大于另一个Student对象的age,返回1,否则返回-1

 

获取Student对对象

调用TreeSet对象的add()方法,参数:Student对象

遍历集合

import java.util.TreeSet;public class TreeSetDemo {  /**   * @param args   */  public static void main(String[] args) {    TreeSet<Student> treeset=new TreeSet<Student>();    treeset.add(new Student("taoshihan1",30));    treeset.add(new Student("taoshihan2",20));    treeset.add(new Student("taoshihan3",40));    for(Student student:treeset){      System.out.println(student.name+"==="+student.age);    }              }}class Student implements Comparable<Student>{    public int age;  public String name;  public Student(String name,int age) {    this.name=name;    this.age=age;  }  @Override  public int compareTo(Student o) {    if(o.age<this.age){      return 1;    }else{      return -1;    }  }  }

 

 

结果:

taoshihan2===20

taoshihan1===30

taoshihan3===40

 




原标题:[javaSE] 集合框架(TreeSet)

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

lazada可以做吗:https://www.goluckyvip.com/tag/85143.html
lazada一天能出多少单:https://www.goluckyvip.com/tag/85144.html
lazada如何入驻lazmall:https://www.goluckyvip.com/tag/85145.html
lazada怎么上传新产品:https://www.goluckyvip.com/tag/85147.html
lazada分站点吗:https://www.goluckyvip.com/tag/85149.html
最终价值费:https://www.goluckyvip.com/tag/8515.html
大同旅游攻略一日游 山西大同一日游旅游景点有哪些:https://www.vstour.cn/a/408251.html
如何从帽儿山到哈尔滨火车站(详细交通路线及注意事项):https://www.vstour.cn/a/408252.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流