自定义集合排序与随机生成制定范围随机整数(笔记)

话不多说,直接上代码。。。

先建实体类Student

package test;

public class Student {

    private String No; // 学号
    private String Name; // 姓名
    private int Score; // 成绩

    public String getNo() {
        return No;
    }

    public void setNo(String no) {
        No = no;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public int getScore() {
        return Score;
    }

    public void setScore(int score) {
        Score = score;
    }

    public Student(String no, String name, int score) {
        super();
        No = no;
        Name = name;
        Score = score;
    }
}

主类

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class Demo2 {

    public static void main(String[] args) {
        String clas = "1702";
        Random random = new Random();
        List studentList = new ArrayList();
        for (int i = 1; i <= 30; i++) {
            // 生成60-100随机数/生成指定范围随机数min到max格式:random.nextInt(max-min+1)+min;
            int sci = random.nextInt(100 - 60 + 1) + 60; 

            if (i < 10) {
                studentList.add(new Student(clas + "0" + i, "姓名" + i, sci));
            } else {
                studentList.add(new Student(clas + i, "姓名" + i, sci));
            }           
        }

        studentList=sortList(studentList);

        for (int i = 0; i < studentList.size(); i++) {
            Student student = studentList.get(i);
            System.out.println("学号:" + student.getNo() + ", 姓名:" + student.getName() + ", 成绩:" + student.getScore());
        }
    }

    /** * list集合排序 * 根据成绩降序 * @param list * @return */
    public static List sortList(List list) {

        Collections.sort(list, new Comparator() {

            @Override
            public int compare(Student s1, Student s2) {
                // TODO > 升序 | < 降序
                if (s1.getScore() < s2.getScore()) {
                    return 1;
                }
                if (s1.getScore() ==  s2.getScore()) {
                    return 0;
                }
                return -1;
            }           
        });
        return list;        
    }

}

你可能感兴趣的:(java)