TreeSet Sort Related Summary

Source: Internet
Author: User
Tags comparable

Java Collection This piece is used more in the work, some things always forget, so record down here. TreeSet principle
1. Features
      • TreeSet are used for sorting, you can specify a sequence in which the objects are stored in the order specified
2. How to use
  • A. natural order (comparable)
      • The Add () method of the TreeSet class promotes the stored object to the comparable type
      • The CompareTo () method of the calling object is compared to the object in the collection ( who is currently credited, who will call the CompareTo method )
      • Stored according to the results returned by the CompareTo () method
  • B. Comparator order (Comparator)
      • Create a treeset when you can make a comparator
      • If a subclass object of comparator is passed in, the TreeSet is sorted in the order of the comparator
      • The Add () method internally calls the Compare () method in the comparator interface to sort
      • The object being called (that is, the currently deposited object) is the first parameter of the Compare method, and the object in the collection (the object that has been added) is the second parameter of the Compare method
  • C. Two different ways of difference
      • TreeSet constructors do not pass anything, by default in the order of comparable in the class (no error ClassCastException)
      • TreeSet if the comparator is passed in, priority is given to comparator

TreeSet Sort Related Summary

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.