Notes for using TreeSet in java-15.4 from the beginning
Next, we will continue to discuss the things to be noted when using TreeSet.
2. TreeSet
Features:
(1) elements are ordered.
(2) elements are repeated and need to be de-duplicated
(3) The Comparable interface must be implemented.
(4) the underlying data storage is based on the tree structure.
Let's modify the code in the previous chapter:
Package com. ray. ch15; import java. lang. reflect. InvocationTargetException; import java. util. Set; import java. util. TreeSet; public class Test
{Public static
Set
Fill (Set
Set, Class
Type) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {for (int I = 0; I <10; I ++) {set. add (type. getConstructor (int. class ). newInstance (I);} return set;} public static
Void test (Set
Set, Class
Type) throws syntax, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {fill (set, type); System. out. println (set);} public static void main (String [] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {test (new TreeSet
(), TreeType. class); // test (new TreeSet
(), SetType. class); // java. lang. ClassCastException // test (new TreeSet
(), HashType. class); // java. lang. classCastException} class SetType {private int id = 0; public int getId () {return id;} public void setId (int id) {this. id = id;} public SetType (int I) {id = I ;}@ Overridepublic String toString () {return id + "" ;}@ Overridepublic boolean equals (Object obj) {return obj instanceof SetType & (id = (SetType) obj ). id) ;}} class HashType extends SetType {public HashType (int I) {super (I) ;}@ Overridepublic int hashCode () {return getId ();}} class TreeType extends HashType implements Comparable
{Public TreeType (int I) {super (I) ;}@ Overridepublic int compareTo (TreeType o) {if (o. getId ()> getId () {// sort return-1;} else {if (o. getId () = getId () {// return 0;} else {return 1 ;}}}}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Explain the above Code:
(1) fill Method: adds data to the imported set through generics and reflection.
(2) test method: We fill data in the set multiple times to see if the set is de-duplicated.
(3) SetType: the original type, but the equals and toString methods are implemented simply. toString indicates the object through the output id.
(4) HashType: inherits SetType, and then implements the hashCode method to throw an exception.
(5) TreeType: implements the Comparable interface. We have deduplicated and sorted the compareTo method. If we only do one of them, we only implement one function.
Summary: This chapter mainly discusses the notes for using TreeSet.
This chapter is here. Thank you.