英文:
How to sort an arrayList when the datatype is not a string Java?
问题
我有一个存储对象的ArrayList。每个对象包含字符串和整数。如何根据对象的字符串对这个ArrayList进行字母排序?(我尝试过使用Collections.sort(arrayList的名称),但由于ArrayList的数据类型不是字符串,它不会进行排序。)
英文:
I have an arrayList that stores objects. Each object contains string and integer. How can I sort this arrayList alphabetically based on the object's string? (I tried Collections.sort(arrayList's name) but since the arrayList's data type isn't a string, it won't sort.)
答案1
得分: 1
你需要传递一个自定义的比较器:
Collections.sort(list, (o1, o2) -> o1.getString().compareTo(o2.getString()));
或者实现Comparable接口:
public class YourClass implements Comparable<YourClass> {
...
@Override
public int compareTo(YourClass other) {
//TODO: 错误处理
return this.getString().compareTo(other.getString());
}
}
//然后:
//Collections.sort(list);
英文:
You have to pass a custom Comparator:
Collections.sort(list,(o1,o2)->o1.getString().compareTo(o2.getString());
or implement the Comparable interface:
public class YourClass implements Comparable<YourClass>{
...
@Override
public int compareTo(YourClass other){
//TODO: Error handling
return this.getString().compareTo(other.getString();
}
}
//and then:
//Collections.sort(list);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论