• 締切済み

JavaのArrays.sortについて教えてください

 Javaを勉強している初心者です。 次のプログラムはある学校のある学年の梅組の生徒5人のデータ(出席番号 no、氏名 name、身長 height)を 身長の低い順に並べ替えようとするものです。クラスMainでArrays.sort(ume);を実行するとどんな処理が行われるのか、またクラスStudentのメソッドcompareTo(Object o)はどう関係するのかご教示ください。 import java.util.Arrays; class Student implements Comparable { private int no; private String name; private double height; public Student(int no, String name, double height) { this.no = no; this.name = name; this.height = height; } public int compareTo(Object o) { double h1 = this.height; double h2 = ((Student)o).height; if(h1 == h2) { return 0; } else if(h1 > h2) { return 1; } else { return -1; } } } public class Main { public static void main(String[] args) { Student[] ume = new Student[5]; ume[0] = new Student(2, "木下 薫", 141.5); ume[1] = new Student(5, "湯水 敦", 145.0); ume[2] = new Student(1, "相田 徹", 152.5); ume[3] = new Student(4, "田中 大", 136.0); ume[4] = new Student(3, "橋 航", 145.0); Arrays.sort(ume); } }

みんなの回答

  • BLUEPIXY
  • ベストアンサー率50% (3003/5914)
回答No.1

参考URLに書かれている通りです。 >クラスMainでArrays.sort(ume);を実行するとどんな処理が行われるのか 配列ume がStudent クラスの compareTo を適用して、それぞれの大小関係からソートされます。 >compareTo(Object o)はどう関係するのか 配列の要素を整列(ソート)するときにそれぞれのオブジェクトの順序を決定する必要があります。 Arrays.sort から呼び出されてそれぞれのオブジェクト順序を決める為に使われます。

参考URL:
http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/java/util/Arrays.html#sort(java.lang.Object[])
KuroGin
質問者

お礼

BLUEPIXY殿 早速のご回答ありがとうございました。 Arrays.sortとcompareToとの関係がわかりました。 ご提示いただいた参考資料を調べて更に理解を深めるつもりです。                  KuroGin

関連するQ&A

  • JAVAのComparableについて・・・

    compareto()を使って名前、身長、体重を「身長昇順」拡張for文でだしたいのですが・・・ (1)returnを使って何を返せばいいのか? (2)System.out.println()でなにをすればいいのか? (3)他の文で間違っているのか? この3点が分かりません。JAVAに詳しい方よろしくお願いします。。。 package class; public class NewClass { public static void main(String[] args) { NewClass2 A = new NewClass2("aaa", 160, 40); NewClass2 B = new NewClass2("bbb", 170, 60); NewClass2 C = new NewClass2("ccc", 150, 70); System.out.println("---Comparable---"); Set<Comparable> ts3 = new TreeSet<Comparable>(); ts3.add(A); ts3.add(B); ts3.add(C); for(Comparable cm : ts3) { System.out.println(?????????????); } package class; public class NewClass2 implements Comparable< NewClass2> { private String name; private int Weight; private int Height; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getWeight() { return this.Weight; } public void setWeight(int Weight) { this.Weight = Weight; } public int getHeight() { return this.Height; } public void setHeight(int Height) { this.Height = Height; } public StudentBean(String name, int Height, int Weight) { this.name = name; this.Weight = Weight; this.Height = Height; } @Override public int compareTo(Object arg0) { StudentBean sb = (StudentBean)arg0;     String name1 = this.name; int Height1 = this.Height; int Weight1 = this.Weight;     int returnval = 0; if(Height1 > sb.getHeight()) { returnval = 1; } else if(Height1 < sb.getHeight()) { returnval = -1; } else returnval = 0; } return ???????; } 文は以上です 出力は aaa 160 40 ・ ・ ・ なかんじでお願いします。

  • JAVAのComparableについて・・・

    compareto()を使って名前、身長、体重を「身長昇順」拡張for文でだしたいのですが・・・ (1)returnを使って何を返せばいいのか? (2)System.out.println()でなにをすればいいのか? (3)他の文で間違っているのか? この3点が分かりません。JAVAに詳しい方よろしくお願いします。。。 package class; public class NewClass { public static void main(String[] args) { NewClass2 A = new NewClass2("aaa", 160, 40); NewClass2 B = new NewClass2("bbb", 170, 60); NewClass2 C = new NewClass2("ccc", 150, 70); System.out.println("---Comparable---"); Set<Comparable> ts3 = new TreeSet<Comparable>(); ts3.add(A); ts3.add(B); ts3.add(C); for(Comparable cm : ts3) { System.out.println(?????????????); } package class; public class NewClass2 implements Comparable< NewClass2> { private String name; private int Weight; private int Height; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getWeight() { return this.Weight; } public void setWeight(int Weight) { this.Weight = Weight; } public int getHeight() { return this.Height; } public void setHeight(int Height) { this.Height = Height; } public StudentBean(String name, int Height, int Weight) { this.name = name; this.Weight = Weight; this.Height = Height; } @Override public int compareTo(Object arg0) { StudentBean sb = (StudentBean)arg0;     String name1 = this.name; int Height1 = this.Height; int Weight1 = this.Weight;     int returnval = 0; if(Height1 > sb.getHeight()) { returnval = 1; } else if(Height1 < sb.getHeight()) { returnval = -1; } else returnval = 0; } return ???????; } 文は以上です 出力は aaa 160 40 ・ ・ ・ なかんじでお願いします。

  • 継承プログラムについて 

    下記で作成した継承プログラムで、間違ったプログラムの部分を直しても同じエラーが発生します。どうしたら下記のプログラムがうまく動きますか? ちなみに同じエラーが発生するのはsuper()の部分で、シンボルが見つからないとのこと. class Human { private double height, weight; private String name; private static int count = 0; public Human() { height = 0; weight = 0; name = "no name"; } public void inputData(String na, double ht, double wt) { height = ht; weight = wt; name = na; } public void showValue() { count++; System.out.println("名前: " + name + ", 身長: " + height + "cm, 体重:"+ weight + "kg"); } public void copyData(Human a) { height = a.height; weight = a.weight; name = a.name; } public double readData(double a) { if(a==0){ return height; }else{ return weight; } } public static int readCount() { return count; } } class Sandai extends Human { private String number; public Sandai(String nu, String na, double ht, double wt) { super(na, ht, wt); number = nu; } public void showData() { System.out.println("学籍番号:"+number+", "); showValue(); } } class Kadai12_3 { public static void main(String args[]) { Sandai student = new Sandai("09H099", "Taro", 165.0, 55.0); student.showData(); } }

    • ベストアンサー
    • Java
  • 継承プログラムについて

    下記で作成した継承プログラムで、間違ったプログラムの部分を直しても同じエラーが発生します。どうしたら下記のプログラムがうまく動きますか? ちなみに同じエラーが発生するのはsuper()の部分で、新保ぷが見つからないとのこと。 class Human { private double height, weight; private String name; private static int count = 0; public Human() { height = 0; weight = 0; name = "no name"; } public void inputData(String na, double ht, double wt) { height = ht; weight = wt; name = na; } public void showValue() { count++; System.out.println("名前: " + name + ", 身長: " + height + "cm, 体重:"+ weight + "kg"); } public void copyData(Human a) { height = a.height; weight = a.weight; name = a.name; } public double readData(double a) { if(a==0){ return height; }else{ return weight; } } public static int readCount() { return count; } } class Sandai extends Human { private String number; public Sandai(String nu, String na, double ht, double wt) { super(na, ht, wt); number = nu; } public void showData() { System.out.println("学籍番号:"+number+", "); showValue(); } } class Kadai12_3 { public static void main(String args[]) { Sandai student = new Sandai("09H099", "Taro", 165.0, 55.0); student.showData(); } }

    • ベストアンサー
    • Java
  • java これはオーバーロードすればいいのでは?

    以下のようなコードについて質問です。 class Person { public static int count = 0; public String firstName; public String middleName; public String lastName; public int age; public double height; public double weight; Person(String firstName, String lastName, int age, double height, double weight) { Person.count++; this.firstName = firstName; this.lastName = lastName; this.age = age; this.height = height; this.weight = weight; } Person(String firstName, String middleName, String lastName, int age, double height, double weight) { this(firstName, lastName, age, height, weight); this.middleName = middleName; } public String fullName() { if(middleName == null){ return this.firstName + " " + this.lastName; }else{ return this.firstName + " "+middleName+ ""+ this.lastName; } } fullName() メソッドを条件分岐して、以下のようなメソッドで、ミドルネームを入れるかどうかで、条件分岐するということなのですが… class Main { public static void main(String[] args) { Person person1 = new Person("Kate", "Jones", 27, 1.6, 50.0); person1.printData(); Person person2 = new Person("John", "Christopher", "Smith", 65, 1.75, 80.0); person2.printData(); Person.printCount(); } } これって、引数にfullNameメソッドに何も指定してなくていいのでしょうか。 疑問に感じてしまいました。 また、同じfullNameメソッドという名前のメソッドで引数でmiddleNameの有無だけ変えてオーバーロードしてはだめなのでしょうか。

  • 空白にはなにを入れればいいのでしょうか?

    [A君,50,60,70] -> 180 [Bさん,90,70,80] -> 240 [C君,30,40,45] -> 115 という3教科の試験の合計点を学生毎に表示するものですが、<?>の部分になんと書けばいいのかわかりません。。教えてください。 import java.lang.*; import java.io.*; import java.util.*; class Student { private String name; private int[] score; public Student (String name, int[] score){ this.name = name; this.score = score; } public Student(String name, int x, int y, int z){ this.score = new int[3]; } public String toString(){ String s = "[" + name; for (int i=0; i < score.length; i++){ s += “ , “ + score[1]; } s += "]"; return s; } public int total(){ int sum = 0; for (int i=0; i<<?>; i++){ <?> } return sum; } } class StudentTest { public static void main(String[] args){ Student[] data = { new Student("A君",50,60,70), new Student("Bさん",90,70,80), new Student("C君",30,40,45), }; for (int i=0; i<data.length; i++){ System.out.println("" + data[i] + "\t-> " + data[i].total()); } } }  

    • ベストアンサー
    • Java
  • javaの課題が難しくて解けません。力を貸してください

    本日、プログラムの授業で課題が出されました。 解ける方がいましたら、回答を教えてください。 課題:これまでの演習で作成した Rectangle, Triangle, Circle, Trapezoidクラスを利用するクラス (メインクラス)を修正して, コマンドライン引数から図形の種類、入力値を指定できるようにしてみよ。 ※4つのクラスをpackageで1つにまとめる必要があるようです。 お手数かけますが、宜しくお願いします。 下記が演習で作成した4つのクラスになります。参考にしてください。 (Rectangleクラス) import java.io.*; class Rectangle { private int width; private int height; public Rectangle(int w, int h) { width = w; height = h; } public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } public int getWidth() { return width; } public int getHeight() { return height; } public double calcArea() { return width * height; } public void show() { System.out.println("width=" + getWidth() + ", height= " + getHeight()); } } public class kadai1 { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("width= "); String str1 = br.readLine(); System.out.print("height= "); String str2 = br.readLine(); Rectangle r = new Rectangle(Integer.parseInt(atr1),Integer.parseInt(str2)); r.show(); System.out.println("面積 = " + r.calcArea()); } } (Triangleクラス) public double calcArea() { return width * height / 2.0; } (Circleクラス) public double calcArea() { return Math.PI * radius * radius; } public void show() { System.out.println("radius= " + getRadius()); } (Trapezoidクラス) public double calcArea() { return (upper + lower) * height / 2.0; } public void show() { System.out.println("upper= " + getUpper() + ", lower= " + getLower() + ", height= " + getHeight()); }

  • compareToについて

    質問なのですが、 package projecjava4t; import java.util.Arrays; /** * Program の概要の説明です */ public class Program { public static void main(String[] args) { Girl[] a=new Girl[4]; a[0] = new Girl("candy", 100); a[1] = new Girl("Lisa", 1010); a[2] = new Girl("Ann",1020); a[3] = new Girl("Eliza",1030); Arrays.sort(a); int i; for(i=0;i<a.length;i++)   a[i].disp(); } } class Girl implements Comparable { String name; int age; public Girl(String s, int a){ name = s; age = a; } public void disp(){ System.out.println("名前"+name+"年齢"+age); } public int compareTo(Object g){ return -(age - ((Girl)g).age); } } のArrays.sort(a)のcompareTo(Object g)では、どのようなことが起きてるのかわかりません。 あと、-(age - ((Girl)g).age)の意味がよくわからないのですが、 わかる方いらしたらご教授よろしくお願いします。

    • ベストアンサー
    • Java
  • Java クラスを使ったソート

    Javaで隣接交換法を用いて配列dataを昇順に並び替え、出力するプログラムを作成する。 ただし、ループ処理には、int型の変数は使わず、以下のCounterクラスを使用する。 という課題が出て、とり組んでみたのですが所々よく分からないので、お力添えしていただければと思います。 課題には下記のような条件が書いてありました。 配列data={54,76,32,89,45,11,8,54,29,67}; [クラス] Counter [インスタンス変数] int型の値を保持するcount [コンストラクタ] 引数で渡された値を初期値としてインスタンス変数に設定する。 引数を省略された場合、ゼロを設定する。 [メソッド] increment 値に1加算する decrement 値に1減算する compareTo 以下の処理を行う Counterの保持している値が引数に指定された値と 等しい場合、値0を返す。 Counterの保持している値が引数に指定された値より 小さい場合、0より小さい値を返す。 Counterの保持している値が引数に指定された値より 大きい場合、0より大きい値を返す。 get Counterの保持している値を添え字として、 引数で渡された配列の要素を取得します。 set Counterの保持している値を添え字として、 第1引数で渡された配列に第2引数で渡された値を設定します。 以下組んだものです。 ---- class Counter { int count = 0; Counter(int count) { this.count = count; } Counter() { this.count = 0; } public int get(int[] data) { return this.count; } public void set(int[] data, int count) { this.count = count; } public void increment() { this.count = count + 1; } public void decrement() { this.count = count - 1; } public int compareTo() { return count; } } public class Lesson09 { public static void main(String args[]) { Counter counter = new Counter(0); int[] data = {54, 76, 32, 89, 45, 11, 8, 54, 67}; counter.get(data); counter.set(data, 0); } } ---- とりあえず、compareToとsetとgetの部分をどう記述していいのかがよく分かりません。 よろしくお願いします。

    • ベストアンサー
    • Java
  • [Java]Javaの文法が間違っているのでしょうか・・・?

    6人分の小テストの点数を記録し,平均点,最高点,平均点以下の人の一覧を計算するプログラムを作成したいのです。 入力はコマンドラインから行います。 しかし,TEST配列がうまく初期化がうまく記述できないため,コンパイル時点で”シンボルが見つけられません”というエラーが出てしまいます。 Javaの経験が浅いので、文法そのものが間違っているか心配です。C言語についてはある程度知識がありますから、C言語と対比して教えて頂けたりすると大変たすかります。 宜しくお願い致します。 class Lecture { static Lecture[] TEST; static double avg=0; static int max=0; static int i = 0; static String kamoku; int scorebox; String name; String student_number; Lecture(int size){ TEST = new Lecture[size]; for (int i = 0; i < size; i++) { Exercise a = new Exercise(); Student b = new Student(); TEST[i] = new Lecture(a,b); } } static void add(Exercise score, Student aStudent) { TEST[i].name = aStudent.name; TEST[i].student_number = aStudent.student_number; TEST[i].scorebox = score.score; i++; } static void avg() { int sum=0; for (int i = 0; i < 6; i++) { sum += TEST[i].scorebox; } avg = sum / 6; } static void max() { int max = 0; int temp = 0; for (int i = 0; i < 6; i++) { if (max < TEST[i].scorebox) { temp = i; max = TEST[i].scorebox; } } max = i; } static void show_kamoku(){ System.out.println("科目:"+kamoku); } static void show(){ Lecture.max(); System.out.println("平均点:"+avg); System.out.println("最高得点者:"+TEST[max]); } static void under_avg(){ Lecture.avg(); System.out.println("平均点を下回った者"); for(int i=0 ; i<6 ; i++){ if(avg > TEST[i].scorebox){ System.out.println(TEST[i]); } } } } class Exercise { int score; Exercise(int score) { this.score = score; } Exercise() { } public String toString() { return " 得点:" + score; } } class Student { String name; String student_number; Student(String student_number,String name ) { this.name = name; this.student_number = student_number; } Student() { } public String toString() { return "学籍番号:" + student_number + " 名前:" + name; } } class ExerciseEvaluation { public static void main(String args[]){ Lecture.kamoku=args[0]; Lecture[] lec = new Lecture[6]; Student Y0 = new Student(args[1],args[2]); Exercise X0 = new Exercise(Integer.parseInt(args[3])); lec[0].add(X0, Y0); Student Y1 = new Student(args[4], args[5]); Exercise X1 = new Exercise(Integer.parseInt(args[6])); lec[1].add(X1, Y1); Student Y2 = new Student(args[7], args[8]); Exercise X2 = new Exercise(Integer.parseInt(args[9])); lec[2].add(X2, Y2); Student Y3 = new Student(args[10], args[11]); Exercise X3 = new Exercise(Integer.parseInt(args[12])); lec[3].add(X3, Y3); Student Y4 = new Student(args[13], args[14]); Exercise X4 = new Exercise(Integer.parseInt(args[15])); lec[4].add(X4, Y4); Student Y5 = new Student(args[16], args[17]); Exercise X5 = new Exercise(Integer.parseInt(args[18])); lec[5].add(X5, Y5); Lecture.show_kamoku(); Lecture.show(); Lecture.under_avg(); } }

専門家に質問してみよう