java 中根据类的属性排序
2024-08-27 04:20:58
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);
}
}
}
最新文章
- JavaScript分离代码理解
- linux一些常用配置
- 使用jasperreports-5.6.0.jar导致的问题
- 字符流和字节流(FileReader类和FileWriter类)
- Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
- BAT-使用BAT方法清理系统垃圾
- 第一章 USB Type C的基本原理
- cocos2d-x-lua基础系列教程三(lua面向对象)
- Delphi基本图像处理方法汇总
- .net 笔试题目
- PADS Layout VX.2.3 出Gerber文件时遇到一个奇怪的现象
- LeetCode算法题-Subtree of Another Tree(Java实现)
- Jquery遍历之获取子级元素、同级元素和父级元素
- 两个时间点计算相隔几年,几个月,几天-java
- Golang——垃圾回收GC(2)
- set集合遍历
- Swift5 语言指南(二十) 类型转换
- MySQL Disk--磁盘相关参数
- [翻译] VENCalculatorInputView
- TeamWork#1,Week 5,Suggestions for Team Project