The elements stored in the Set interface are not repeated.
Hashset can check duplicates. When using Hashset to customize generics, you can add equals() and hashCode() automatic generation methods to generic classes to realize equal element duplicate checking.
TreeSet can be sorted. When you use TreeSet to customize generics, you can automatically add implementation methods to interfaces in generic classes:
@Override public int compareTo(Day3_test4 o) { return o.getName().equals(this.getName())?0:this.getAge()-o.getAge(); }
The return value 0 is used for duplicate checking. If it is 1, duplicate checking is not required. The returned difference is the sorting method.
You can also add a comparer when creating a TreeSet:
Setsets=new TreeSet<>(new Comparator() { @Override public int compare(Day3_test4 o1, Day3_test4 o2) { return o1.getName().equals(o2.getName())?0:o1.getAge()-o2.getAge(); } });
In the same way, the return value of 0 is used for duplicate checking. If it is 1, duplicate checking is not needed. If it is o1-o2, it is in positive order, otherwise it is in reverse order.
Use Treeset to create a custom collection, which is sorted according to the total score of students:
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Set<Vocjd3> sets = new TreeSet<>(new Comparator<Vocjd3>() { @Override public int compare(Vocjd3 o1, Vocjd3 o2) { return o1.getName().equals(o2.getName()) ? 0 : o2.getzof() - o1.getzof(); } }); for (int i = 0; i < 3; i++) { System.out.print("Please enter your name:"); String name = scanner.nextLine(); System.out.print("Please enter your Chinese score:"); int yuwen = Integer.parseInt(scanner.nextLine()); System.out.print("Please enter your math score:"); int shuxue = Integer.parseInt(scanner.nextLine()); System.out.print("Please enter your English score:"); int yingyu = Integer.parseInt(scanner.nextLine()); sets.add(new Vocjd3(name, yuwen, shuxue, yingyu)); } for (Vocjd3 set : sets) { System.out.println(set); } }