Set class and sub-class:
TreeSet ordered sub-class;
HashSet unordered (hash) sub-class
The contents of the HashSet subclass are not sequential, and the individual elements are not duplicated (except for the object).
set<string> allset = new hashset<string> () Allset.add ("a");//Duplicate Data Allset.add ("B"); Allset.add ("B"); Allset.add ("C"); Allset.add ("D");//Duplicate Data Allset.add ("E"); Allset.add ("E"); Allset.add ("F"); System.out.println (Allset);
TreeSet Order:
The TreeSet sub-class implements the Sortset subclass (sort) interface, TreeSet interfaces can be sorted.
When you add a custom object to the TreeSet class, the custom object requires a CompareTo ordering method in the comparable interface, otherwise it will report: Class conversion exception
Java.lang.ClassCastException
may need to be in the replication ToString () method, otherwise the error when printing:
[Email protected], [email protected], [email protected]
For example:
When adding data, there is a custom class: The person class, 2 elements, name (first name), age, and, if sorted by age, the repetition age is eliminated.
Person
public class Person implements comparable<person> {private String name;private int age;public person (String name, in T age) {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.) {this.age = age;} @Overridepublic String toString () {return name: "+ name +", Age: "+ ages +" ";} public int compareTo (person o) {//TODO auto-generated method stub if (This.age > O.age) {return 1;} else if (This.age < o.age) {return-1;} Else{return 0;}}}
Setdemo2:
set<person> allset = new treeset<person> (), Allset.add (New person ("Zhang San"), Allset.add (New person ("John Doe", 30 ), Allset.add (New person ("Harry")), Allset.add ("Zhao Liu"), Allset.add (New person ("Tianqi", 32)); System.out.println (Allset);
The results are as follows:
[Name: Zhang San, age: 30, Name: Harry, Age: 31, Name: Tianqi, Age: 32]
Therefore, should be replicated in addition to sorting comparable CompareTo method, but also should be implemented: Equles (),
Java:set classes and subclasses: TreeSet ordered sub-class, HashSet unordered sub-class