在Java中对对象的ArrayList进行排序
我有一个对象,它包含一个int值、一个字符串和一个double。该对象的实例存储在ArrayList中。我现在想打印那个对象,但我想先按字符串值对ArrayList排序。我很难通过像选择排序这样的方式来概念化我将如何做到这一点。任何帮助都将不胜感激 这是我认为你应该做的,但那似乎不起作用在Java中对对象的ArrayList进行排序,java,sorting,object,arraylist,Java,Sorting,Object,Arraylist,我有一个对象,它包含一个int值、一个字符串和一个double。该对象的实例存储在ArrayList中。我现在想打印那个对象,但我想先按字符串值对ArrayList排序。我很难通过像选择排序这样的方式来概念化我将如何做到这一点。任何帮助都将不胜感激 这是我认为你应该做的,但那似乎不起作用 public static void sSortStrings(ArrayList<Student> list) { //Selection sort int count1; i
public static void sSortStrings(ArrayList<Student> list) { //Selection sort
int count1;
int count2;
int largest;
String temp;
for (count1 = 0; count1 < list.size() - 1; count1++) {
largest = 0;
for (count2 = largest + 1; count2 < list.size() - count1; count2++) {
if (list[largest].compareTo(list[count2]) < 0) {
largest = count2;
}
}
temp = list[list.size() - 1 - count1];
list[list.size() - 1 - count1] = list[largest];
list[largest] = temp;
}
}
公共静态无效SSortString(ArrayList列表){//选择排序
int count1;
int count2;
int最大;
字符串温度;
对于(count1=0;count1
顺便说一句,我的教授在源代码中包含了这个,但我不确定我是否应该调用它而不是compare to方法
public boolean nameComesBefore(Student other) {
return name.compareToIgnoreCase(other.name) < 0;
}
public boolean namesbefore(学生其他){
返回name.compareToIgnoreCase(other.name)<0;
}
假设学生
类具有字符串属性的getter。
然后,对列表进行排序只需执行list.sort(Comparator.comparing(Student::getName))
这将按学生姓名对给定列表进行排序。
有关更多选项,请查看javadoc中的和。欢迎使用堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您以后仍然有问题,请随时回来,提供一份能够证明您的问题的报告。我认为Comparable将满足您的需要。您可以访问此网站了解更多信息