重写Comparable 接口 我现在List中放了一个实体类Student 、 Student中有属性name,我想将list中的student排序 第一个显示的是name等于我指定的一个字符串。大神们 怎么写、最好能附上code. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 Collections.sort(studentList, new Comparator<Student>() { public int compare(Student s1, Student s2) { return s1.getName().length() - s2.getName().length(); } });差不多这样,你就改改其中代码就行了,应该可以排序 compare在这个方法中我不是两个实体类中的name比较 类似这样:public int compare(Student s1, String str) { //str是和name比较的对象 return s1.getName().length() - s2.getName().length(); } 但是这样好像不行 compare在这个方法中我不是两个实体类中的name比较 类似这样:public int compare(Student s1, String str) { //str是和name比较的对象 return 1; } package exercises;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Student implements Comparable { String name; int num; Student(String name, int num) { this.name = name; this.num = num; } @Override public int compareTo(Object o) { Student s = (Student) o; return name.compareTo(s.name) > 0 ? 1 : (name.compareTo(s.name) == 0 ? 0 : -1); } public String toString() { return "name of student is: " + this.name; } public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(new Student("zhangsan", 1)); list.add(new Student("lisi", 2)); list.add(new Student("wangwu", 3)); Collections.sort(list); for (Student s : list) { System.out.println(s); } }} SSH+proxool问题!! 无法从已删除行获取值 oracle sql怎么写循环语句 js传入中文到action是乱码,怎么解决啊 JSP加载swf文件(在线文档阅读)的问题 给Java web版的朋友们散分~ 请帮忙看看啊!怎么才能把邮件发出去 在目录树中,如何实现“点击文字和点击文字前面的图标”产生一样的下拉效果。 在查询输入框中输入一些关键字就会出现一个下拉列表可以选择是怎么做到的 .war用什么软件打开 求高人指点,webEQApplet.jar怎么使用啊! weblogic10设置线程数
return s1.getName().length() - s2.getName().length();
}
});差不多这样,你就改改其中代码就行了,应该可以排序
public int compare(Student s1, String str) { //str是和name比较的对象
return s1.getName().length() - s2.getName().length();
} 但是这样好像不行
public int compare(Student s1, String str) { //str是和name比较的对象
return 1;
}
import java.util.Collections;
import java.util.List;public class Student implements Comparable {
String name;
int num; Student(String name, int num) {
this.name = name;
this.num = num;
} @Override
public int compareTo(Object o) {
Student s = (Student) o;
return name.compareTo(s.name) > 0 ? 1
: (name.compareTo(s.name) == 0 ? 0 : -1);
} public String toString() {
return "name of student is: " + this.name;
} public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("zhangsan", 1));
list.add(new Student("lisi", 2));
list.add(new Student("wangwu", 3));
Collections.sort(list);
for (Student s : list) {
System.out.println(s);
}
}
}