TreeSet ordered sub-class;
HashSet unordered sub-class
Repeating elements, object objects are filtered by equals and hashcode.
If you replace the TreeSet in the example above with HashSet, then the code will not filter from the object
HashSet unordered subclasses, how to filter duplicate objects? (a single element can be filtered, but the same object does not)
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{//if age is the same, you need to determine name, repeat return This.name.compareTo (o.name);}}
SETDEMO3:
set<person> allset = new hashset<person> () Allset.add (New person ("Zhang San", 30));//Duplicate Object Allset.add (new person (" ("Zhang San"), Allset.add ("John Doe"), Allset.add (New person ("Harry"), Allset.add (New person ("Zhao Liu", 31)); Allset.add (New person ("Tianqi", 32)),//Duplicate object Allset.add (new person ("Tianqi", 32)); System.out.println (Allset);
Output Result:
[Name: Harry, Age: 31, Name: Tianqi, Age: 32, Name: Tianqi, Age: 32, Name: Zhang San, age: 30, Name: Zhang San, age: 30, Name: John Doe, age: 30, Name: Zhao Liu, age: 31]
In this case, you need to filter out duplicate objects, then person also need to replicate equels, and hashcode two methods, these two methods to filter duplicate objects:
public int hashcode () {return This.name.hashCode () * this.age;} public boolean equals (Object o) {if (this = = O) {return true;} if (! ( o instanceof person) {return false;} Person P = (person) o;if (this.name.equals (p.name) && this.age = = p.age) {return true;} Else{return false;}}
Results of execution:
[Name: Zhao Liu, Age: 31, Name: John Doe, age: 30, Name: Zhang San, age: 30, Name: Harry, Age: 31, Name: Tianqi, Age: 32]
Java:set Object TreeSet ordered subclass, HashSet unordered subclass, repeating object two