請把學生名與考試分數錄入到Map中,並按分數顯示前三名成績學員的名字


import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;


public class TestCollections1{

public static void main(String[] args) {

   

  public int compare(Object o1, Object o2) {//對比必須寫全了,否則由於set爲無序,不可重複集合,易導致丟失元素。

            if (o1 instanceof Student && o2 instanceof Student) {

            Student e1=(Student)o1;

            Student e2=(Student)o2;

            int  i=e1.getScore()-(e2.getScore());

            if(i==0){

            return e1.getId()-(e2.getId());

            }return i;

            }

            return 0;

        }            

    };

    Map map =new TreeMap(com);

    map.put(new Student(99, 001), "小米");

    map.put(new Student(69, 003), "紅米");

    map.put(new Student(79, 006), "大米");

    map.put(new Student(89, 005), "咪咪");

    //通過entrySet方法把Map類型轉化爲Set集合。        

    Set entry=map.entrySet();

    //把Set集合轉化爲List集合

    List list =new ArrayList(entry);   

    Collections.reverse(list);

    System.out.println("前三名姓名爲:");

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

        System.out.println(list.get(i));

    }

}

}


class Student{

private int score;

private int id;

public int getScore() {

return score;

}

public void setScore(int score) {

this.score = score;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + id;

result = prime * result + score;

return result;

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Student other = (Student) obj;

if (id != other.id)

return false;

if (score != other.score)

return false;

return true;

}

public Student(int score, int id) {

super();

this.score = score;

this.id = id;

}

@Override

public String toString() {

return "Student [score=" + score + ", id=" + id + "]";

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章