|
1 , Concept:
The set set is an unordered set of disallowed duplicates, so-called disallow re-duplex refers to the set collection if the Access object, by default, will call the Hashcode and Equals method to compare the object is equal, set the bottom of the combination is the map set of key, so is unordered, The following describes the implementation class for the hashset of the set set and the TreeSet implementation class
2 , Hashset
By creating objects, use the following:
set<person> set = new hashset<> ();
The "<>" above means that generics are similar to the previous list collection, when HashSet adds data to the collection, the program automatically calls the Hashcode method to get the hashcode value, and if the result is different, it is considered to be a different object and is added to the collection. If the hashcode is the same, then call the Equals method to compare the values of each property, further confirm whether it is the same set, and not add if all are the same
If you add a custom object to the collection (in addition to the string data type and the base data type, which removes the system's own data type), the programmer is required to override the Hashcode method and the Equals method to determine whether the two objects are equal, and if the equality is not added to the collection, If not equal, the following error (type conversion exception) will be reported if the two methods are not overridden:
The reason is because the custom-built class does not rewrite the hashcode and Equals method, then the collection in the judgment of two objects can not be judged, all will be error
3 , TreeSet
By creating objects, use the following:
treeset<integer> set = new treeset<> ();
TreeSet collections and HashSet collections are different, treeset is to sort the collection in natural order, and if you need to send the data to the collection, you need to implement and rewrite the CompareTo in the interface comparable () method to determine whether two objects are equal and to sort the objects in the collection according to each property condition, and can help to remove duplicates if the caller is greater than the argument return positive represents ascending, and vice versa represents descending
4 , TreeSet the custom sort (Comparator )
Custom sorting is achieved by creating a new class to implement the comparable method in the comparator interface to achieve the custom ordering, the custom ordering is the use of the TreeSet construction method, you can directly pass to the construction method of their own written custom ordering to make the following:
treeset<student> TreeSet2 = new TreeSet (new Mycomparator ());
where comparator () is a custom sorted class written by the programmer, the example is as follows:
|