我得到:
List<Comment> list = new ArrayList<Comment>();
我的类注释包含:ID,名称和日期;我得到了一些添加指定评论的功能,但我想在此之后按日期降序排序我的列表。如何做到这一点:
Collections.sort(list, comparator)
?
您必须
实现一个基于日期字段实现compare
方法的Comparator<Comment>
,并将此对象传递给Collections.sort
。
下面是一个完整的示例:
import java.util.*;
class Comment {
String id, String name;
Date date;
public Comment(String id, String name, Date date) {
this.id = id;
this.name = name;
this.date = date;
}
}
class CommentComparator implements Comparator<Comment> {
public int compare(Comment o1, Comment o2) {
return o1.date.compareTo(o2.date);
}
}
class Test {
public static void main(String[] args) {
List<Comment> comments = new ArrayList<Comment>() {{
long now = System.currentTimeMillis();
add(new Comment("id1", "second", new Date(now)));
add(new Comment("id2", "first", new Date(now - 1000)));
add(new Comment("id3", "third", new Date(now + 1000)));
}};
Collections.sort(comments, new CommentComparator());
}
}
你已经知道你需要做什么了。只需实现 de Comparator
.它可以是这样的:
Collections.sort(list, new Comparator<Comment>() {
@Override
public int compare(Comment o1, Comment o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
(您可能需要检查空值(
研究员在这里提到的一个选项是为注释实现自定义比较器。另一种方法是在注释类中实现可比较接口。
import java.util.*;
class Comment implements Comparable<Comment> {
private String id, String name;
private Date date;
public Comment(String id, String name, Date date) {
this.id = id;
this.name = name;
this.date = date;
}
public int compareTo(Comment comment) {
return date.compareTo(o2.date); //Look Ma! Date is Comparable too!
}
}
class Test {
public static void main(String[] args) {
List<Comment> comments = new ArrayList<Comment>() {{
long now = System.currentTimeMillis();
add(new Comment("id1", "second", new Date(now)));
add(new Comment("id2", "first", new Date(now - 1000)));
add(new Comment("id3", "third", new Date(now + 1000)));
}};
Collections.sort(comments);
}
}
我在示例中使用了一些@aioobe代码。