java对vector动态数组中的对象排序,以下代码有何问题,如何修改?

importjava.util.Comparator;importjava.util.Vector;publicclassStudent{Stringname;intsc... import java.util.Comparator;import java.util.Vector;public class Student { String name; int score; public Student(String n, int s) { name = n; score = s; } public boolean equals(Object o) { Student other = (Student) o; return other.score == score; } public String toString() { return name + "," + score; } public static void main(String[] args) { Vector<Student> stu = new Vector<Student>(); stu.add(new Student("张三", 90)); stu.add(new Student("李四", 80)); stu.add(new Student("小明", 85)); stu.add(new Student("王五", 60)); stu.add(new Student("何六", 70)); Student index = new Student("", 60); int t = stu.indexOf(index); System.out.println("成绩为60的学生姓名为" + stu.elementAt(t).name); /* //冒泡排序 for (int i = 0; i < stu.size()-1; i++) { for (int j = 0; j < stu.size()-1-i; j++) { if (stu.get(j).score < stu.get(j+1).score) { Student tmp1 = stu.get(j+1); Student tmp2 = stu.get(j); stu.set(j, tmp1); stu.set(j+1, tmp2); } } } */ //使用Arrays, Collections的sort方法排序 stu.sort(new Comparator<Student>() { public int compare(Student o1, Student o2) { if (o1.score > o2.score) return -1; else if (o1.score < o2.score) return 1; else return 0; } }); System.out.println("对上述记录按照成绩降序排列后的结果为:"); for(Student s : stu) { System.out.println(s); } }} 展开
 我来答
来宾你好闯天涯
2017-09-29 · TA获得超过3876个赞
知道大有可为答主
回答量:4086
采纳率:64%
帮助的人:789万
展开全部

package com.tx.collection;


import java.util.Comparator;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

import java.util.TreeSet;

import java.util.Vector;


public class Student {

String name;

int score;


public Student(String n, int s) {

name = n;

score = s;

}


public boolean equals(Object o) {

Student other = (Student) o;

return other.score == score;

}


public String toString() {

return name + "," + score;

}


public static void main(String[] args) {

Vector<Student> stu = new Vector<Student>();

stu.add(new Student("张三", 90));

stu.add(new Student("李四", 80));

stu.add(new Student("小明", 85));

stu.add(new Student("王五", 60));

stu.add(new Student("何六", 70));

Student index = new Student("", 60);

int t = stu.indexOf(index);

System.out.println("成绩为60的学生姓名为" + stu.elementAt(t).name);


Set<Student> set = new TreeSet(new Comparator<Student>() {

@Override

public int compare(Student o1, Student o2) {

if (o1.score > o2.score)

return -1;

else if (o1.score < o2.score)

return 1;

else

return 0;

}

});

set.addAll(stu);

Iterator<Student> iterator = set.iterator();

while(iterator.hasNext()){

Student s = iterator.next();

System.out.println(s.name+":"+s.score);

}

}

}

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2017-09-29
展开全部
恐怕要先换成ArrayList,才好排序了

~
~
~
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式