###目的
Comparableインタフェースを用いて,Collections.sortメソッドでソート。
また、これをComparatorインタフェースで実装。
###問題点
int型で起動できないためInteger型にして比べましたが、データの順序が逆になるだけで点数順で上手くソート出来ません。
また、Collectios.sortでのソートが出来ないので、Comparatorインタフェースでのソートも出来ていません。
###ソースコード
import java.util.ArrayList; import java.util.Collections; public class SortScoreComparable { public static void main(String[] args) { ArrayList<Score> score = new ArrayList<Score>(); score.add(new Score("taro", 12, 97)); score.add(new Score("jiro", 42, 54)); score.add(new Score("sabu", 42, 47)); score.add(new Score("siro", 57, 97)); score.add(new Score("goro", 87, 40)); score.add(new Score("roku", 99, 99)); score.add(new Score("nana", 14, 23)); score.add(new Score("hati", 42, 54)); System.out.println("ソート前"); for (Score s : score) { System.out.println(s.getName() + " : Math: " + s.getMath() + " : English : " + s.getEnglish()); } Collections.sort(score); System.out.println("ソート後"); for (Score s : score) { System.out.println(s.getName() + " : Math: " + s.getMath() + " : English : " + s.getEnglish()); } } } class Score implements Comparable<Score> { private String name; private int math; private int english; public Score(String name, int math, int english) { this.name = name; this.math = math; this.english = english; } public String getName() { return name; } public int getMath() { return math; } public int getEnglish() { return english; } public int compareTo(Score another) { Integer Math = new Integer(math); Integer i = new Integer(another.getMath()); if (Math.compareTo(i) < 0) { //自分が相手よりも低い return -1; } else if (Math.compareTo(i) > 0){ //自分が相手よりも高い return 1; } else { //それ以外=同一順位 return 0; } } }
###備考
順序付けは,数学の成績が良い順とし,数学の成績が同点の場合は,英語の成績が良い順とし,それでも順序が付かない場合は同位とする。
多いかとは思いますが、どなたかお願いします。
回答2件
あなたの回答
tips
プレビュー