2017-10-14 50 views
-1

我想将两个不同的List对象合并到另一个List中,并且我必须对它们进行排序。 我上课像下面如何将两个不同的List对象合并到一个List中并对它们进行排序

类员工和一流的工作人员这两个类实现可比和排序基于时间戳是长期价值

List<Employee> empList=new ArrayList<>(); 
    List<Staff> staffList=new ArrayList<>(); 
    Employee emp1=new Employee(3, "EPPI CF", 1507542925000l); 
    Employee emp2=new Employee(2, "EPPI CF2", 1507542924000l); 
    Employee emp3=new Employee(1, "EPPI CF3", 1507543156000l); 
    empList.add(emp1); 
    empList.add(emp2); 
    empList.add(emp3); 
    Collections.sort(empList); 
    Staff staff1=new Staff(1, "Parnamya", 1507724760000l); 
    Staff staff2=new Staff(2, "Sreenu", 1507623378000l); 
    Staff staff3=new Staff(3, "Joseph", 1507621774000l); 
    Staff staff4=new Staff(4, "Dolores", 1507547700000l); 
    Staff staff5=new Staff(5, "Molly", 1507541100000l); 
    staffList.add(staff1); 
    staffList.add(staff2); 
    staffList.add(staff3); 
    staffList.add(staff4); 
    staffList.add(staff5); 
    Collections.sort(staffList); 
    List<Object> allObj=new ArrayList<>(); 
    allObj.addAll(empList); 
    allObj.addAll(staffList); 

我想排序最后名单是基于时间戳ALLOBJ(长值)在这两个对象中共同的属性是时间戳。

我该怎么做?

预期输出:

[Staff [id=1, staffName=Parnamya, timestamp=1507724760000], 
Staff [id=2, staffName=Sreenu, timestamp=1507623378000], 
Staff [id=3, staffName=Joseph, timestamp=1507621774000], 
Staff [id=4, staffName=Dolores,timestamp=1507547700000], 
[ 
    Employee [id=1, name=EPPI CF3, timstamp=1507543156000], 
    Employee [id=3, name=EPPI CF, timstamp=1507542925000], 
    Employee [id=2, name=EPPI CF2, timstamp=1507542924000], 
    Staff [id=5, staffName=Molly, timestamp=1507541100000] 
] 
+0

但'员工'和'员工'共享一个共同的接口?如果不是,那么你会发现很难创建一个可以比较一种类型的比较器。 – Bobulous

+0

嗨,非常感谢你的回复。我没有得到你的问题,两个类都实现了Comparable接口。 – user3355101

+0

@ user3355101是的,但是你能比较一个员工和一个员工吗? –

回答

4

你需要让他们延长了相同的超类或实现相同的接口比较。让他们都扩展类如下应该工作:

public abstract class TimeStamped implements Comparable<TimeStamped>{ 

@Override 
public int compareTo(TimeStamped timedObject) { 
    return Long.compare(this.getTimeStamp(), timedObject.getTimeStamp()); 
} 

public abstract long getTimeStamp(); 

} 
+0

很长时间比较好的电话,不知道存在。通过空检查,你的意思是if语句来检查timedObject是否为空?如果是这种情况,我不确定是否要继续比较。 – luckydog32

+0

是的,忘记'null',我的错误,它应该会抛出'NullPointerException' – Oleg

+0

嗨lickydog32谢谢你的答案。我试着用上面的解决方案得到下面的输出 [Employee [id = 1,name = EPPI CF3,timstamp = 1507543156000],Employee [id = 3,name = EPPI CF,timstamp = 1507542925000],Employee [id = 2,name = EPPI CF2,timstamp = 1507542924000],Staff [id = 1,staffName = Parnamya,timestamp = 1507724760000],Staff [id = 2,staffName = Sreenu,timestamp = 1507623378000],Staff [id = 3,staffName = Joseph,timestamp = 1507621774000],Staff [id = 4,staffName = Dolores,timestamp = 1507547700000],Staff [id = 5,staffName = Molly,timestamp = 1507541100000]],但在问题 – user3355101

相关问题