How to get a reversed list view on a list in Java?

前端 未结 12 773
自闭症患者
自闭症患者 2020-11-28 21:05

I want to have a reversed list view on a list (in a similar way than List#sublist provides a sublist view on a list). Is there some function which provides this

12条回答
  •  一生所求
    2020-11-28 21:26

    Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.

    Ergo,

    Collections.reverse(list.clone());
    

    If you are using a List and don't have access to clone() you can use subList():

    List shallowCopy = list.subList(0, list.size());
    Collections.reverse(shallowCopy);
    

提交回复
热议问题