HashSet de-duplication (judge duplicate mechanism)
14. HashSet: unordered, non-repeatable collection, thread-unsafe, underlying based on HashMap, based on hashCode();
Mechanism for judging repetition:
- Determine whether the current element is equal to the element hashCode() to be added
- If hashCode() is equal, then check whether the current element is equal to equals(). If so, the two elements are considered the same
TreeSet to reorder the mechanism
TreeSet: an unordered, non-repeatable set, thread-unsafe, based on a red-black tree.
Judge repetition and sorting mechanisms:
Natural ordering
The target element class implements the Comparable interface, overriding the compareTo() method
- Positive number: indicates different elements, ascending order
- Negative number: represents different elements, in descending order
- 0: indicates the same element
Code examples:
Define a natural ordering of the User class, ascending by age and descending by name length
public class User implements Comparable<User>{
private String name;
private int age;
//get,set, constructor,toString...
@Override
public int compareTo(User o) {
if(this.age >o.age){
/ / ascending
return 1;
}else if(this.age <o.age){
return -1;
}else {
if(this.name.length()>o.name.length()){
/ / descending
return -1;
}else if(this.name.length()<o.name.length()){
return 1;
}else {
return 0; }}}}Copy the code
Testing:
public class Demo {
public static void main(String[] args) {
TreeSet<Object> treeSet = new TreeSet();
treeSet.add(new User("Zhang".17));
treeSet.add(new User("Li Sisi".17));
treeSet.add(new User("Li Sisi, yes, yes, yes.".18));
treeSet.add(new User("Li Sisi said.".18)); System.out.println(treeSet); }}Copy the code
Results:
Custom sorting
When creating the TreeSet object, pass in a Comparator subclass object and override the compare() method
- Positive number: indicates different elements, ascending order
- Negative number: represents different elements, in descending order
- 0: indicates the same element
Note: Custom sorting takes precedence over natural sorting
Code examples:
Define the comparator UserComparetor for the User class, descending by age and ascending by name length
public class UserComparetor implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
if(o1.getAge() >o2.getAge()){
return -1;
}else if(o1.getAge() <o2.getAge()){
return 1;
}else {
if(o1.getName().length()>o2.getName().length()){
return 1;
}else if(o1.getName().length()<o2.getName().length()){
return -1;
}else {
return 0; }}}}Copy the code
Testing:
public class Demo {
public static void main(String[] args) {
TreeSet<Object> treeSet = new TreeSet(new UserComparetor());
treeSet.add(new User("Zhang".17));
treeSet.add(new User("Li Sisi".17));
treeSet.add(new User("Li Sisi, yes, yes, yes.".18));
treeSet.add(new User("Li Sisi said.".18)); System.out.println(treeSet); }}Copy the code
Results: It can be seen that when both natural and custom sort exist, custom sort has higher priority