【问题标题】:How to use an iterator to copy a list如何使用迭代器复制列表
【发布时间】:2015-09-12 18:33:36
【问题描述】:

如果我有一个列表,并且我想要一个返回列表而不暴露实际列表本身的方法,那么最好的方法是什么?

public class open {
    private List<Open> users;

    public open() {
        this.users = new ArrayList<Open>();
    }
    public List<Open> getUsers() {
      //return a copy of the list}

所以基本上我需要一个列表的副本...我猜使用迭代器可能是可行的方法,但有没有更有效的方法呢?

【问题讨论】:

    标签: java list arraylist iterator


    【解决方案1】:

    有很多选择。

    你可以使用复制构造函数:

    return new ArrayList<>(users);
    

    这将显式复制List 并返回副本。除非你真的需要一个可变副本,否则我不会推荐这个 - 显然是 O(n)

    更有效的方法是使用Collections 实用程序类,这提供了一种返回不可变视图的方法:

    return Collections.unmodifiableList(users);
    

    由于这是一个视图,返回方法是O(1) 而不是O(n) 所以效率更高。它处理确保您不能修改List,既不能通过addremove 等也不能通过例如Iterator.remove

    【讨论】:

      【解决方案2】:

      不需要创建列表的副本。您可以使用Collections.unmodifiableList 返回列表的不可修改视图。

      return Collections.unmodifiableList(users);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-20
        • 2018-04-26
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        相关资源
        最近更新 更多