reidxx
V2EX  ›  Java

继承相同基类的不同类型对象,有没有办法进行排序比较

  •  
  •   reidxx · Nov 4, 2019 · 3439 views
    This topic created in 2401 days ago, the information mentioned may be changed or developed.

    基类 BaseEntity:

    Long id;
    LocalDateTime createAt;
    LocalDateTime updateAt;
    

    子类 A extends BaseEntity

    子类 B extends BaseEntity

    用泛型可以把 A B 对象塞到一个集合里 List<? super BaseEntity> list。

    现在想对这个集合的元素根据 createAt 字段进行排序,用 Lambda.sort() 无法实现,编译阶段就提示错误了。

    如上,有没有办法可以实现排序呢?

    3 replies    2019-11-04 17:35:04 +08:00
    gaifanking
        1
    gaifanking  
       Nov 4, 2019   ❤️ 1
    直接用 List<BaseEntity>啊
    根据 PECS,不能又 add,又遍历
    cigarzh
        2
    cigarzh  
       Nov 4, 2019
    TreeList 写个 Comparator 行不
    reidxx
        3
    reidxx  
    OP
       Nov 4, 2019
    @anjxue #1 哈哈,我傻了,谢谢大佬,原来根本不需要泛型。。

    @cigarzh #2 一楼方法就行了,谢谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5801 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 06:13 · PVG 14:13 · LAX 23:13 · JFK 02:13
    ♥ Do have faith in what you're doing.