1.自然排序
通过实现Compareble接口中的CompareTo方法,达到排序的目的。CompareTo的返回值有三种:0,正数,负数。正负数表示按升降序,0表示数值一样,应采用第二种排序方法。
比如:按照年龄升序排列,年龄一样时按姓名首字母排序。主函数关键代码如下:
TreeSet<Student>stu=new TreeSet<>();
stu.add(new Student("熊二",15));
stu.add(new Student("熊大",16));
stu.add(new Student("蹦蹦",14));
stu.add(new Student("吉吉",14));
for (Student student : stu) {
System.out.println(student);
}
在Student类里面这样写:
public class Student implements Comparable<Student> {//实现泛型接口
private String Name;
private int Age;
@Override //按住alt+insert快速填充
public String toString() {
return "Student{" +
"Name='" + Name + '\'' +
", Age=" + Age +
'}';
}
public Student(String name, int age) {
this.Name = name;
this.Age = age;
}
@Override
public int compareTo(Student stu) { //重写方法
int result=this.Age-stu.Age;
if(result==0)
{
result=this.Name.compareTo(stu.Name)*-1;//视情况选择谁减谁
}
return result;
}
}
2.比较器
比较器是接口Comparator中的Compare方法,原理和自然排序的接口相似,不过可以采用匿名类来实现,可以简化代码。注意:要在创建TreeSet对象的时候就要将匿名类对象传入集合的构造方法中。主函数关键代码:
TreeSet<Teacher> teacher=new TreeSet<>(new Comparator<Teacher>() {//匿名类
@Override
public int compare(Teacher teacher1, Teacher teacher2) {
int result=teacher1.getAge()-teacher2.getAge();
if(result==0)
{
result=teacher1.getName().compareTo(teacher2.getName());
}
return result;
}
});
teacher.add(new Teacher("zhangsan",21));
teacher.add(new Teacher("lisi",23));
teacher.add(new Teacher("wangwu",18));
teacher.add(new Teacher("zhangsan",18));
for (Teacher teach : teacher) { //增强for循环,本质上是迭代器
System.out.println(teach);
}
}
teacher类就是一个普通的类,不需要实现接口
3.可变参数的使用
即函数的参数列表可以有0个或多个参数,本质上是数组。语法:参数类型... 变量名
public static int GetSum(int... args)
{
int sum=0;
for(int i=0;i<args.length;i++)
{
sum+=args[i];
}
return sum;
}
这样就可以在调用该函数时,传入不同个参数均可以返回相应的结果。