Arrays类
inttemp[] = {3,5,7,9,1,2,6,8};//声明一个整形数组
Arrays.sort(temp);//数组排序
System.out.println(Arrays.toString(temp));// 以字符串输出数组 [1, 2, 3, 5, 6, 7, 8, 9]
intpoint = Arrays.binarySearch(temp,3);// 检索数据位置
System.out.println("元素'3'的位置在:"+ point);//元素'3'的位置在:2
Arrays.fill(temp,3);//填充数组
System.out.println(Arrays.toString(temp));// 以字符串输出数组 [3, 3, 3, 3, 3, 3, 3, 3]
Comparable接口
public class Student implements Comparable {//指定类型为Student
private String name;
private int age;
private float score;
public Student(String name,int age,float score) {
this.name= name;
this.age= age;
this.score= score;
}
publicString toString() {
returnname+"\t\t"+age+"\t\t"+score;
}
@Override
public int compareTo(Student o) {// 覆写compareTo()方法,实现排序规则的应用
if(this.score> o.score) {
return -1;
}else if(this.score< o.score) {
return 1;
}else{
if(this.age> o.age){
return 1;
}else if(this.age< o.age){
return -1;
}else{
return 0;}}}}
main
Student stu[] = {new Student("张三",20,90.0f),new Student("李四",22,90.0f),new Student("王五",20,99.0f),new Student("赵六",20,70.0f),new Student("孙七",22,100.0f)};
java.util.Arrays.sort(stu);// 进行排序操作
for(int i =0; i < stu.length; i++) {
System.out.println(stu[i]);
}
//返回如下:
自定义比较规则:
//定义学生类
public classStudents {
privateStringname;
private intage;
publicStudents(String name,intage) {
this.name= name;
this.age= age;
}
public booleanequals(Object obj) {
if(this== obj){
return true;
}
if(!(objinstanceofStudents)){
return false;
}
Students stu = (Students) obj;
if(stu.name.equals(this.name)&&stu.age==this.age){
return true;
}else{
return false;
}
}
publicString toString() {
returnname+"\t\t"+age;
}
publicString getName() {
returnname;
}
public voidsetName(String name) {
this.name= name;
}
public intgetAge() {
returnage;
}
public voidsetAge(intage) {
this.age= age;
}
}
// 定义比较规则
public classStudentComparatorimplementsComparator {//实现比较器接口
@Override
public intcompare(Students s1, Students s2) {// 为学生类定义比较规则
if(s1.equals(s2)){
return0;
}else if(s1.getAge() < s2.getAge()){
return1;
}else{
return-1;
}
}
}
// 为对象数组排序
Students student[] = {new Students("张三",20),new Students("李四",22),new Students("王五",20),new Students("赵六",22)};
java.util.Arrays.sort(student,newStudentComparator());//排序,指定排序规则
for(inti =0; i < student.length; i++) {
System.out.println(student[i]);
}
//返回如下: