Java Review of TreeSet

Source: Internet
Author: User

Last learned HashSet, and then come to know it a friend TreeSet, it can ensure that the elements out of sort state

TreeSet supports two sorts of sorting methods: natural Sorting and custom sorting.
The natural sort is the default sort, which sorts the elements from small to large, and he invokes the element's CompareTo (Object obj) to compare the sizes between the elements and then sorts them in ascending order.
So it implements the comparable interface. For example Obj1.compareto (OBJ2), returns 0 equals, returns a positive number, and returns a negative number <.
If you attempt to add an object to TreeSet, the object class must implement the comparable interface.
For example

Class Test{}public class Err {public static void main (string[] args) {TreeSet tset=new treeset<> (); Tset.add (New Test ());//The first line has only one element, so there is no comparison, there is no error tset.add (new test ());//The second line, because the comparable interface is not implemented, so there is no comparison, so this guild error TreeSet newtreeset= New Treeset<> (); Newtreeset.add (New String ("abc")); Newtreeset.add (new Date ());//Add different types of data, So although all two classes implement the comparable interface, they cannot be compared, so there is an error.}

The same class of objects should be added to the collection at the same time, otherwise an exception will occur

  



Java Review of TreeSet

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.