Java Collection framework Summary: Sorting of TreeSet classes (1)

Source: Internet
Author: User

TreeSet supports two sorting methods: Natural sorting and custom sorting. TreeSet uses natural sorting by default.

1. Natural sorting

TreeSet calls the compareTo (Object obj) method of the Set element to compare the size relationship between elements, and then sorts the set elements in ascending order. This is a natural sorting method. The premise of comparison: The two objects have the same type ).

Java provides a Comparable interface, which defines a compareTo (Object obj) method. This method returns an integer and the class implementing this interface must implement this method, the object of the class implementing this interface can be compared. When an object calls this method to compare it with another object, for example, obj1.comparTo (obj2), if this method returns 0, the two objects are equal. If a positive integer is returned, it indicates that obj1 is greater than obj2. If this method returns a negative integer, it indicates that obj1 is less than obj2.

Common java classes implement the Comparable interface and provide a relatively large standard. Common classes for implementing the Comparable interface:

  • BigDecimal, BigIneger, and all numeric corresponding packaging classes: Compare them by their corresponding values.
  • Character: Compare the Character UNICODE values.
  • Boolean: the package class instance corresponding to true is greater than false.
  • String: Compare the UNICODE values of the characters in the String.
  • Date and Time: the subsequent Time and Date are larger than the previous Time and Date.

If you try to add an object to a TreeSet, the class of this object must implement the Comparable interface.

The following program reports an error:

 
 
  1. Class Err
  2. {
  3. }
  4. Public class TestTreeSetError
  5. {
  6. Public static void main (String [] args)
  7. {
  8. TreeSet ts = new TreeSet ();
  9. // Add two Err objects to the TreeSet
  10. Ts. add (new Err ());
  11. Ts. add (new Err ());
  12. }
  13. }
  14.  

Note:

The above program tries to add two Err objects to the TreeSet set. When the first object is added, there is no element in the TreeSet, so there is no problem. When the second Err Object is added, treeSet calls the compareTo (Object obj) method of the Object to compare with other elements in the set. If the corresponding class does not implement the Comparable interface, a ClassCastException is thrown. In addition, ClassCastException is still thrown when you try to retrieve the first element from the TreeSet.

When you use the compareTo (Object obj) method to compare objects, you must forcibly convert the Object obj to the same type, because only two instances of the same class can compare the size. That is, the objects added to the TreeSet should be the same class. Otherwise, a ClassCastException is thrown. For example, if you add a String object to the TreeSet, this operation is completely normal. When the second Date Object is added, TreeSet calls the compareTo (Object obj) method of the Object to compare it with other elements in the set. In this case, an exception is thrown.

In actual programming, programmers can define their own classes to add multiple types of objects to the TreeSet, provided that the user-defined class implements the Comparable interface, when this interface is implemented, the compareTo (Object obj) method is not forcibly converted. However, when the set data in the TreeSet is operated, the ClassCastExceptio exception still occurs for different types of elements. Read it carefully)

When an Object is added to a TreeSet set, TreeSet calls the compareTo (Object obj) method of the Object to compare the size with other objects in the container, and then determines its storage location based on the red-black tree algorithm. If the two objects are equal through compareTo (Object obj), TreeSet considers them to store the same location.

For a TreeSet set, it determines that two objects are not equal by the following criteria: two objects are compared using the equals method to return false, or comparw.bject obj) 0 is not returned for comparison -- even if two objects are the same, TreeSet treats them as two objects.

The procedure is as follows:

 
 
  1. // Z class, override the equals method, always return false,
  2. // Override the compareTo (Object obj) method and always return a positive integer
  3. Class Z implements Comparable
  4. {
  5. Int age;
  6. Public Z (int age)
  7. {
  8. This. age = age;
  9. }
  10. Public boolean equals (Object obj)
  11. {
  12. Return false;
  13. }
  14. Public int compareTo (Object obj)
  15. {
  16. Return 1;
  17. }
  18. }
  19. Public class TestTreeSet
  20. {
  21. Public static void main (String [] args)
  22. {
  23. TreeSet set = new TreeSet ();
  24. Z z1 = new Z (6 );
  25. Set. add (z1 );
  26. System. out. println (set. add (z1 ));
  27. // Output the set below. Two elements are displayed.
  28. System. out. println (set );
  29. // Modify the age attribute of the first element of the set.
  30. (Z) (set. first (). age = 9;
  31. // Output the age attribute of the last element of the set, which is changed to 9.
  32. System. out. println (Z) (set. last (). age );
  33. }
  34. }

Program running result:

true [TreeSet.Z@1fb8ee3, TreeSet.Z@1fb8ee3] 9

Note:

The program adds the same Object twice, because the equals () method of the z1 Object always returns false, and the compareTo (Object obj) method always returns 1. In this way, the TreeSet considers that the z1 object is different from its own, so two z1 objects are added to the TreeSet. The two elements stored in the TreeSet object are actually the same element. Therefore, when the age attribute of the first element in the TreeSet set is modified, the age attribute of the last element in the TreeSet set is also changed.

Conclusion: When you need to put an Object into the TreeSet, override the equals () method of the corresponding class of the Object, ensure that the method has the same result as the compareTo (Object obj) method, the rule is: if two objects return true after comparison through the equals method, the two objects return 0 after comparison using the compar1_bject obj method.

If the two objects return true through the equals method comparison, but the two objects do not return 0 when compared using the compareTo (Object obj) method, this will cause the TreeSet to save the two objects in different locations, so that both objects can be added successfully, which is a little different from the Set rules.

If the two objects return 0 through the compareTo (Object obj) method, but they use the equals method to compare and return false, it will be more troublesome: because the two objects use the comparatebject obj method to compare equal, treeSet will try to save them in the same location, but it doesn't actually work. Otherwise, only one object will be left.

If a variable object is added to the TreeSet and the attributes of the variable object are modified by the subsequent program, the sequence of the variable object size changes with that of other objects, however, TreeSet does not adjust their order again, and may even cause the two objects to be saved in the TreeSet. If they are compared using the equals method, true and comparw.bject obj are returned.

The procedure is as follows:

 
 
  1. Class R
  2. {
  3. Int count;
  4. Public R (int count)
  5. {
  6. This. count = count;
  7. }
  8. Public String toString ()
  9. {
  10. Return "R (count attribute:" + count + ")";
  11. }
  12. Public boolean equals (Object obj)
  13. {
  14. If (obj instanceof R)
  15. {
  16. R r = (R) obj;
  17. If (r. count = this. count)
  18. {
  19. Return true;
  20. }
  21. }
  22. Return false;
  23. }
  24. Public int hashCode ()
  25. {
  26. Return this. count;
  27. }
  28. }
  29. Public class TestHashSet2
  30. {
  31. Public static void main (String [] args)
  32. {
  33. HashSet hs = new HashSet ();
  34. Hs. add (new R (5 ));
  35. Hs. add (new R (-3 ));
  36. Hs. add (new R (9 ));
  37. Hs. add (new R (-2 ));
  38. // Print the TreeSet set. The set elements are sorted.
  39. System. out. println (hs );
  40. // Retrieve the first element
  41. Iterator it = hs. iterator ();
  42. R first = (R) it. next ();
  43. // Assign a value to the count attribute of the first element
  44. First. count =-3;
  45. // Output count again. The elements in the TreeSet are unordered.
  46. System. out. println (hs );
  47. Hs. remove (new R (-3 ));
  48. System. out. println (hs );
  49. // Output false
  50. System. out. println ("Does hs contain R objects whose count is-3? "+ Hs. contains (new R (-3 )));
  51. // Output false
  52. System. out. println ("Does hs contain R objects whose count is 5? "+ Hs. contains (new R (5 )));
  53.  
  54. }
  55. }
  56.  

Program running result:

[R (count attribute:-3), R (count attribute:-2), R (count attribute: 5), R (count attribute: 9)]
[R (count attribute: 20), R (count attribute:-2), R (count attribute: 5), R (count attribute:-2)]
[R (count attribute: 20), R (count attribute:-2), R (count attribute: 5), R (count attribute:-2)]
[R (count attribute: 20), R (count attribute:-2), R (count attribute:-2)]

Note:

The R object in the above program is a normal method that overwrites the equals method and comparable method class. Both methods use the count attribute of the R object as the basis for judgment. The results output by the Program for the first time are ordered. When the count attribute of the R object is changed, the output result of the program also changes and contains repeated elements. Once the attribute of the variable element in the TreeSet set is changed, when the object is deleted from the view, the TreeSet will also fail to be deleted or even the original attribute in the set is not modified, but the elements that are equal to the modified elements cannot be deleted .)

When the R object is-2, no elements are deleted. The program can delete the R object whose count is 5, this indicates that TreeSet can delete objects that are not modified and are not duplicated with other objects that are modified.

Summary: processing these objects with HashSet is complex and error-prone. To make the program more robust, we recommend that you put only immutable objects in the HashSet and TreeSet sets.


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.