可变参数
public class Test {
public static void main(String[] args) {
sum();
sum(19);
sum(19,20);
sum(new int[]{19,20});
}
public static void sum(int...nums){
System.out.println("sum接收的是数组,可接收0,1,多个参数,且一个方法只能一个可变参数,且要放在最后面" + Arrays.toString(nums));
}
}
Collections常用api
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Collections.addAll(list ,11,2,3,41,5); //添加多个值
Collections.shuffle(list); //打乱顺序
System.out.println(list);
Collections.sort(list);
System.out.println("排序" + list);
//自定义排序,可以Student类中重写,但不会去重
List<Student> list1 = new ArrayList<>();
Collections.addAll(list1,new Student("小A",10,"男",10.2),
new Student("小B",1,"男",10.2),
new Student("小C",19,"男",10.2),
new Student("小D",19,"男",10.2));
Collections.sort(list1);
System.out.println(list1);
//工具类自带排序
Collections.sort(list1, (o1, o2)-> o2.getAge() - o1.getAge());
System.out.println(list1);
}
}
class Student implements Comparable<Student>{
private String name;
private Integer age;
private String sex;
private double height;
public Student() {
}
public Student(String name, Integer age, String sex , double height) {
this.name = name;
this.age = age;
this.sex = sex;
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", height=" + height +
'}';
}
@Override
public int compareTo(Student o) {
return this.age - o.age;
}
}