发布网友 发布时间:2022-04-22 22:41
共3个回答
热心网友 时间:2023-08-29 16:35
ArrayList中元素的排序是通过equals方法进行的,你把equals方法重写一下,按照你说的时间来排序就好了,至于合并为一个列表就很简单了啊,你先把listA里面的元素加进来,再把listB里面的元素加进来不就行了,如果有重复的话,会加不进去
热心网友 时间:2023-08-29 16:36
package sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class SortBean {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
List<Proct> l1=new ArrayList() ;
List<Proct> l2=new ArrayList();
List<Proct> l3=new ArrayList();
for(int i=0;i<5;i++){
Proct p=new Proct(String.valueOf(i),new Date());
System.out.println(p);
l1.add(p);
Thread.sleep(1000);
}
for(int i=0;i<5;i++){
Proct p=new Proct(String.valueOf(i),new Date());
System.out.println(p);
l2.add(p);
Thread.sleep(1000);
}
l3.addAll(l2);
l3.addAll(l1);
System.out.println("原list--------------------------------");
for(Proct l:l3){
System.out.println(l.getId()+"||"+l.getDate());
}
System.out.println("排序后的list--------------------------------");
Collections.sort(l3);
for(Proct l:l3){
System.out.println(l.getId()+"--"+l.getDate());
}
}
}
package sort;
import java.util.Date;
public class Proct implements Comparable<Proct>{
private String id;
private Date date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Proct(String id, Date date) {
super();
this.id = id;
this.date = date;
}
@Override
public String toString() {
return "Proct [date=" + date + ", id=" + id + "]";
}
@Override
public int compareTo(Proct o) {
// TODO Auto-generated method stub
return this.date.compareTo(o.date);
}
}
proct类实现比较方法就行
然后用collections.sort
热心网友 时间:2023-08-29 16:36
java.util.Collections
static <T> void sort(List<T> list, Comparator<? super T> c)
Sorts the specified list according to the order inced by the specified
List<Proct> list=......;
list=java.util.Collections.sort(list, new Comparator<Proct>(){
public int compare(Proct o1, Proct o2){
return o1.getDate().compareTo(o2.getDate());
}
});追问前辈 能否白话一点