码迷,mamicode.com
首页 > 编程语言 > 详细

Java-TreeSet的用法-入门

时间:2015-12-06 20:44:35      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

Java语言中,Set接口有3种通用实现:HashSetTreeSet,LinkedHashSet。TreeSet是一种能够对内部元素进行排序的集合,它使用红黑树来存储内部元素,基于元素的值进行排序,它比HashSet要慢。

TreeSet要求内部元素实现Comparable接口,因为它是根据元素的compareTo来排序的。下面是一个demo:

package Colloections;

import java.util.LinkedList;
import java.util.TreeSet;

public class TreeSetDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        TreeSet<Person> treeSet = new TreeSet<Person>();
        treeSet.add(new Person("albert", 8));
        treeSet.add(new Person("bob", 5));
        treeSet.add(new Person("bob", 13));
        
        for (Person person : treeSet) {
            System.out.printf(person.toString());
        }
    }
}

class Person implements Comparable<Person>{

    public String name;
    public int age;
    
    public Person(String n, int a){
        name = n;
        age = a;
    }
    
    public  String toString() {
        return String.format("Name is %s, Age is %d%n", name, age);
    }
    
    @Override
    public int compareTo(Person o) {
        // TODO Auto-generated method stub
        int nameComp = this.name.compareTo(o.name);
        return (nameComp != 0 ? nameComp : (this.age - o.age));
    }
    
}

程序输出为:

Name is albert, Age is 8
Name is bob, Age is 5
Name is bob, Age is 13

Java-TreeSet的用法-入门

标签:

原文地址:http://www.cnblogs.com/pzy4447/p/5024197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!