自然排序Comparable的使用
使用空参构造方法创建TreeSet集合
自定义的Student类实现Comparable接口,接口对他实现的每一个类创建了一个接口
package algorithm.set;
import java.util.HashSet;
/**
* @author xiaowang
* @creat 2024/6/7 23:05
* @Description Java Lotus
*/
public class HashSetDemo01 {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
set.add("html");
set.add("javascript");
set.add("java");
set.add("mysql");
if(set.contains("html")){
set.remove("html");
}
for (String s : set) {
System.out.println(s);
}
}
}
package algorithm.set;
import java.util.HashSet;
/**
* @author xiaowang
* @creat 2024/6/7 23:05
* @Description Java Lotus
*/
public class HashSetDemo02 {
public static void main(String[] args) {
HashSet<Student> studentSet=new HashSet<>();
studentSet.add(new Student("熊大", 23));
studentSet.add(new Student("光头强", 24));
studentSet.add(new Student("熊二", 22));
studentSet.add(new Student("熊大", 24));
for (Student student : studentSet) {
System.out.println(student);
}
}
}
package algorithm.set;
import java.util.LinkedHashSet;
/**
* @author xiaowang
* @creat 2024/6/7 23:06
* @Description Java Lotus
*/
public class LinkedHashSetDemo01 {
public static void main(String[] args) {
LinkedHashSet<Integer>set=new LinkedHashSet<>();
set.add(200);
set.add(300);
set.add(100);
set.add(100);
for (Integer integer : set) {
System.out.println(integer);
}
}
}
package algorithm.set;
/**
* @author xiaowang
* @creat 2024/6/7 23:06
* @Description Java Lotus
*/
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(){
}
public Student(String name, int 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 age) {
this.age = age;
}
@Override
public int compareTo(Student stu) {
int result = this.name.compareTo(stu.name);
if(result==0){
result = this.age - stu.age;
}
return result;
}
}
package algorithm.set;
import java.util.HashSet;
import java.util.Set;
/**
* @author xiaowang
* @creat 2024/6/7 23:06
* @Description Java Lotus
*/
public class SetDemo01 {
public static void main(String[] args) {
Set<String>set=new HashSet<>();
set.add("html");
set.add("mysql");
set.add("java");
set.add("mysql");
System.out.println(set);
for (String s : set) {
System.out.println(s);
}
}
}
对于排序的过程中,可能是会出现报错的,使用我们可以去使用comparable接口去进行方法的重载
标签:set,name,String,add,Student,规则,排序,public,TreeSet From: https://blog.csdn.net/Darling912/article/details/139536891