首页 > 编程语言 > 详细

java 中根据类的属性排序

时间:2019-03-29 22:56:42      阅读:340      评论:0      收藏:0      [点我收藏+]
package edu.del;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

class Student implements Comparable<Student>{
String name;
int score;

public Student(String name, int score) {
this.name = name;
this.score = score;
}

public Student() {

}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}

@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", score=" + score +
‘}‘;
}

// @Override
// public int compareTo(Student o) {
// //假如result返回1。Collections.sort(List)方法就是升序;
// //假如result返回-1。Collections.sort(List)方法就是降序;
// int num=new Integer(o.getScore()).compareTo(this.getScore());//这里面是按照降序排列
// //int num=new Integer(this.getScore()).compareTo(this.getScore()); //测试升序
// return num;
//
// }
@Override
public int compareTo(Student o) {
//这里是按照名字字符属性排序
int num =o.getName().compareTo(this.getName());
//int num=this.getName().compareTo(o.getName());
return num;
}
}

public class sort_class {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
System.out.println("请输入学生数量:");
int num =scanner.nextInt();
Student[] student =new Student[num];
List<Student> list =new ArrayList<>();

for (int i = 0; i <num ; i++) {

list.add(new Student(scanner.next(),scanner.nextInt()));
}
Collections.sort(list);

//输出一下看看

for (int i = 0; i <num ; i++) {
System.out.print(list.get(i).getName()+" ");
System.out.println(list.get(i).score);
}
}
}

java 中根据类的属性排序

原文:https://www.cnblogs.com/AnonymousDestroyer/p/10624683.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!