How to use Java-treeset-Getting Started

Source: Internet
Author: User
Tags comparable

In the Java language, the set interface has 3 common implementations HashSet : TreeSet,LinkedHashSet。 TreeSet is a collection of internal elements that can be sorted, using a red-black tree to store internal elements, sorted based on the values of the elements, which is slower than hashset.

TreeSet requires the inner element to implement the comparable interface, because it is sorted according to the CompareTo of the element. Here is a demo:

 Packagecolloections;Importjava.util.LinkedList;ImportJava.util.TreeSet; Public classTreesetdemo { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTreeSet<Person> TreeSet =NewTreeset<person>(); Treeset.add (NewPerson ("Albert", 8)); Treeset.add (NewPerson ("Bob", 5)); Treeset.add (NewPerson ("Bob", 13));  for(person Person:treeset) {System.out.printf (person.tostring ()); }    }}classPersonImplementsComparable<person>{     PublicString name;  Public intAge ;  PublicPerson (String N,inta) {Name=N; Age=A; }         PublicString toString () {returnString.Format ("Name is%s, age is%d%n", name, age); } @Override Public intcompareTo (Person o) {//TODO auto-generated Method Stub        intNamecomp = This. Name.compareto (O.name); return(Namecomp! = 0? Namecomp: ( This. Age-o.age)); }    }

The program output is:

Name is Albert, age is 8
Name is Bob, which is 5
Name is Bob, which is 13

How to use Java-treeset-Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.