How can a TreeSet set ensure that elements are unique?

Source: Internet
Author: User

How can a TreeSet set ensure that elements are unique?

TreeSet:

1. Features

TreeSet is used to sort objects. You can specify an order. objects are sorted in the specified order after they are saved.

2. Usage

A. Comparable)

The add () method of the TreeSet class promotes the stored object to the Comparable type.

Compare the compareTo () method of the called object with the object in the Set (who is currently stored, who will call the compareTo method)

Store the results returned by the compareTo () method

B. Comparator sequence (Comparator)

You can create a Comparator when creating a TreeSet.

If a Comparator subclass object is input, the TreeSet will be sorted by the order in the Comparator.

The add () method automatically calls the compare () method sorting in the Comparator interface.

The called object (the currently saved object) is the first parameter of the compare method, and the object in the Set (the object already added) is the second parameter of the compare method.

C. Differences between the two methods

The TreeSet constructor does not transmit anything. By default, the Comparable class is used (ClassCastException is returned if no Comparable class is used)

If the TreeSet is passed into the Comparator

1. TreeSet stores Integer Elements
Package online. msym. set; import java. util. comparator; import java. util. treeSet; import online. msym. bean. person; public class Demo3_TreeSet {/*** @ param args * The TreeSet set is used to sort object elements, it can also ensure that the element is unique */public static void main (String [] args) {demo1 ();} public static void demo1 () {TreeSet <Integer> ts = new TreeSet <> (); ts. add (3); ts. add (1); ts. add (1); ts. add (2); ts. add (2); ts. add (3); ts. add (3); System. out. println ("TreeSet stores Integer elements:" + ts );}}
2. TreeSet stores custom objects
Package online. msym. set; import java. util. comparator; import java. util. treeSet; import online. msym. bean. person; public class Demo3_TreeSet {/*** @ param args * The TreeSet set is used to sort object elements, it can also ensure that the element is unique * When the compareTo method returns 0, there is only one element in the Set * When the compareTo method returns a positive number, how can the set be saved? * When the compareTo method returns a positive number when a negative number is returned, the set will be stored in reverse order */public static void main (String [] args) {demo2 ();} public static void demo2 () {// because the TreeSet wants to sort the elements, what is the basis for sorting? Name Or the age or others. Tell it. How can we tell it? // The Person class must implement the Comparable interface to override the compareTo method TreeSet <Person> ts = new TreeSet <> (); ts. add (new Person ("Zhang San", 23); ts. add (new Person ("Li Si", 13); ts. add (new Person ("week 7", 13); ts. add (new Person ("Wang Wu", 43); ts. add (new Person ("Zhao ", 33); System. out. println (ts );}}

Note that the output above is the opposite to the added order because the return value of the compareTo Method

Person entity class:

Package online. msym. bean; // There is no hashCode or equals method to simplify the code, you can directly copy the hashCode and equals in the above Person class to public class Person implements Comparable <Person> {private String name; private int age; public Person () {super ();} public Person (String name, int age) {super (); this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Override public String toString () {return "Person [name =" + name + ", age =" + age + "] \ n ";} public int compareTo (Person o) {// return 0; // return 1; return-1 }}
The principle and illustration of TreeSet to ensure unique and natural sorting of Elements

 

TreeSet ensures the principle and illustration of unique and natural sorting of elements, which can be left and right.

 

Sort by age of the Person class, and rewrite the Person class:

// When using this class, it is necessary to generate a null parameter with parameter construction, set and get methods, hashCode and equals method package online. msym. bean; public class Person implements Comparable <Person> {private String name; private int age; @ Override // sort by age public int compareTo (Person o ){
Int num = this. age-o. age; // compare by age
return num;
// Return num = 0? This. name. compareTo (o. name): num; // name is a secondary condition for comparison }}

How TreeSet ensures that elements are unique and sorted by comparator:

Defining the Comparator is to implement the Comparator interface and override the compare and equals methods. However, because all classes inherit the Object by default, and the Object has the equals method,

Therefore, when customizing the comparator class, you do not need to override the equals method, but you only need to override the compare method.

Illustration of the string length comparator:

The following two methods are used: anonymous internal class comparator object, custom comparator object,

Package online. msym. test; import java. util. comparator; import java. util. treeSet; import online. msym. bean. person; public class Demo3_TreeSet {public static void main (String [] args) {// demo1 (); demo2 ();} private static void demo2 () {// requirement: sort the string by length (the length is from large to small using the anonymous internal class object, and the length is the same in descending order of letters) treeSet <String> ts = new TreeSet <> (new Comparator <String> () {@ Override public int compare (String s1, String s2) {int n Um = s2.length ()-s1.length (); // return num = 0? S2.compareTo (s1): num; // The content is a secondary condition}); ts. add ("aaaaaaaa"); ts. add ("z"); ts. add ("wc"); ts. add ("nba"); ts. add ("CBA"); System. out. println (ts);} private static void demo1 () {// requirement: sort the string by length (pass a custom comparator object) treeSet <String> ts = new TreeSet <> (new CompareByLen (); // Comparator c = new CompareByLen (); ts. add ("aaaaaaaa"); ts. add ("z"); ts. add ("wc"); ts. add ("nba"); ts. add ("CBA"); System. out. println (ts) ;} Class CompareByLen/* extends Object */implements Comparator <String> {// implement a Comparator class @ Override public int compare (String s1, String s2) {// compare int num = s1.length ()-s2.length () according to the string length; // The length is the main condition return num = 0? S1.compareTo (s2): num; // The content is a secondary condition }}

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.