3-5编程排序

来源:3-5 编程练习

rock221

2021-01-18 17:53:58

public class Student {

    //成员变量

    private int number;

    private int age;

    private String name;

    

    

    //构造方法

    public Student(){

        

    }

    public Student(int number,int age,String name){

        this.number=number;

        this.age=age;

        this.name=name;

    }

    

    //getter和setter方法

    public void setNumber(int number){

        this.number=number;

    }

    public int getNumber(){

        return number;

    }

    public void setAge(int age){

        this.age=age;

    }

    public int getAge(){

        return age;

    }

    public void setName(String name){

        this.name=name;

    }

    public String getName(){

        return name;

    }

    //toString()方法

    public String toString(){

        return "[学号:"+this.getNumber()+",年龄:"+this.getAge()+",姓名:"+this.getName()+"]";

    }

}

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.Comparator;

//实现Comparator接口

public class StudentTest implements Comparator<Student>{

    

    //实现接口中的方法

   public int compare(Student o1,Student o2){

        String name1=o1.getName();

        String name2=o2.getName();

        int n=name1.compareTo(name2);

        return n;

    }


  

    

    public static void main(String[] args){

        //定义Student类的对象

        Student stu1=new Student(40,20,"peter");

        Student stu2=new Student(28,5,"angel");

        Student stu3=new Student(35,18,"tom");

        

        

        //将对象添加到List中

        List<Student>studentList=new ArrayList<Student>();

        

        

        //输出排序前的数据

        studentList.add(stu1);

        studentList.add(stu2);

        studentList.add(stu3);

        System.out.println("按名字排序前:");

        for(Student test:studentList){

            System.out.println(test);

        }

        //排序

        Collections.sort(studentList,new StudentTest());

        System.out.println("按名字排序后:");

        

      //输出排序后的数据

         for(Student test:studentList){

            System.out.println(test);

         }

    }

}

     

最后有个问题, 是不是只有自定义类进行排序的时候,需要重写compare方法呢, 然后在调用Collections.sort(a,b)方法呢 。

写回答

1回答

好帮手慕阿园

2021-01-18

同学你好,代码完成的不错,很棒;是的,同学的理解是正确的

祝学习愉快~

0

0 学习 · 16556 问题

查看课程