码迷,mamicode.com
首页 > 编程语言 > 详细

java 中根据类的属性排序

时间:2019-03-29 23:34:31      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:ons   system.in   rgs   style   print   ++   pre   pack   pareto   

 1 package edu.del;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.List;
 6 import java.util.Scanner;
 7 
 8 class Student implements Comparable<Student>{
 9     String name;
10     int score;
11 
12     public Student(String name, int score) {
13         this.name = name;
14         this.score = score;
15     }
16 
17     public Student() {
18 
19     }
20 
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28 
29     public int getScore() {
30         return score;
31     }
32 
33     public void setScore(int score) {
34         this.score = score;
35     }
36 
37     @Override
38     public String toString() {
39         return "Student{" +
40                 "name=‘" + name + ‘\‘‘ +
41                 ", score=" + score +
42                 ‘}‘;
43     }
44 
45 //    @Override
46 //    public int compareTo(Student o) {
47 //        //假如result返回1。Collections.sort(List)方法就是升序;
48 //        //假如result返回-1。Collections.sort(List)方法就是降序;
49 //        int num=new Integer(o.getScore()).compareTo(this.getScore());//这里面是按照降序排列
50 //        //int num=new Integer(this.getScore()).compareTo(this.getScore()); //测试升序
51 //        return num;
52 //
53 //    }
54     @Override
55     public int compareTo(Student o) {
56         //这里是按照名字字符属性排序
57         int num =o.getName().compareTo(this.getName());
58         //int num=this.getName().compareTo(o.getName());
59         return num;
60     }
61 }
62 
63 public class sort_class {
64     public static void main(String[] args) {
65         Scanner scanner =new Scanner(System.in);
66         System.out.println("请输入学生数量:");
67         int num =scanner.nextInt();
68         Student[] student =new Student[num];
69         List<Student> list =new ArrayList<>();
70 
71         for (int i = 0; i <num ; i++) {
72 
73             list.add(new Student(scanner.next(),scanner.nextInt()));
74         }
75         Collections.sort(list);
76 
77         //输出一下看看
78 
79         for (int i = 0; i <num ; i++) {
80             System.out.print(list.get(i).getName()+" ");
81             System.out.println(list.get(i).score);
82         }
83     }
84 }

 

java 中根据类的属性排序

标签:ons   system.in   rgs   style   print   ++   pre   pack   pareto   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!