日期:2014-05-20 浏览次数:21139 次
package com.qq.server;
import java.util.Arrays;
import java.util.LinkedList;
public class Test2 {
public static void main(String[] args) {
LinkedList<Student> list = new LinkedList<Student>();
list.add(new Student(1,123));
list.add(new Student(2,113));
list.add(new Student(3,23));
list.add(new Student(4,84));
list.add(new Student(5,423));
list.add(new Student(6,33));
list.add(new Student(7,67));
Student[] tempArray = list.toArray(new Student[] {});
Arrays.sort(tempArray);
for (int i = 0; i < tempArray.length; i++) {
System.out.println(tempArray[i].toString());
}
}
}
class Student implements Comparable {
private Integer studentId;
private double source;
public double getSource() {
return source;
}
public void setSource(double source) {
this.source = source;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public Student() {
}
public Student(Integer studentId, double source) {
this.setStudentId(studentId);
this.setSource(source);
}
public int compareTo(Object stu2) {
int returnInt = 0;
if (this.getSource() - ((Student) stu2).getSource() > 0) {
returnInt = 1;
} else if (this.getSource() - ((Student) stu2).getSource() == 0) {
returnInt = 0;
} else {
returnInt = -1;
}
return returnInt;
}
public String toString() {
return this.getStudentId() + " --> " + this.getSource();
}
}
------解决方案--------------------
package test;
import java.util.Arrays;
public class MyTest {
public static void main(String[] args) {
Student s [] = new Student [4];
s[0] = new Student("aa","001",98);
s[1] = new Student("bb","002",58);
s[2] = new Student("cc","003",78);
s[3] = new Student("dd","004",38);
Arrays.sort(s);
for(int i = 0; i<s.length; i++){
System.out.println(s[i]);
}
}
}
class Student implements Comparable<Student>{
private String name;
private String no;
private int score;
public Student(String name,String no,int score){
this.name = name;
this.no = no;
this.score = score;
}
public int compareTo(Student o) {
// TODO Auto-generated method stub
if(this.score > o.score){
return 1;
}else if(this.score < o.score){
return -1;
}else{
return 0;
}
}
public String toString(){
return "name:"+name+",no:"+no+",score:"+score;
}
}