如何在 Java 中正确返回 ArrayList 的一部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34731034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:14:42  来源:igfitidea点击:

How to properly return part of ArrayList in Java?

javaarraylistsub-array

提问by I Z

I have a class SomeClasswith a static member myMapenter code herethat has the form HasmMap<String,ArrayList<SomeOtherClass>>which gets de-serialized from a file.

我有一个SomeClass带有静态成员的类,该成员myMapenter code here具有HasmMap<String,ArrayList<SomeOtherClass>>从文件中反序列化的形式。

I have a method

我有一个方法

public ArrayList<SomeOtherClass> getList(final String key, final int N)

that is supposed to lookup keyin the map and return the first Nelements of the corresponding ArrayList, or the whole thing if the list has <= Nelements. How should I implement the TODOline below:

应该key在地图中查找并返回相应的第一个N元素ArrayList,或者如果列表有<= N元素则返回整个内容。我应该如何实施以下TODO行:

public ArrayList<SomeOtherClass> getList(final String key, final int N)
{
    ArrayList<SomeOtherClass> arr = myMap.get(key);
    if (arr == null) return null;

    if (arr.size() <= N)
    {
       return arr;
    }
    else
    {
       // TODO: return first N elements
    }
}

to do it efficiently, i.e. without creating unneeded copies in memory while actually returning the right data?

有效地做到这一点,即在实际返回正确数据的同时不在内存中创建不需要的副本?

回答by rgettman

Create a sublist with Lists subListmethod.

使用ListssubList方法创建一个子列表。

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

返回此列表中指定的 fromIndex(包括)和 toIndex(不包括在内)之间的部分的视图。

返回列表受此列表支持,因此返回列表中的非结构性更改会反映在此列表中,反之亦然。

Start at index 0 (inclusive start index), and end at index N(exclusive end index).

从索引 0 开始(包含开始索引),并在索引处N结束(不包含结束索引)。

return arr.subList(0, N);

This does not copy the items to a new list; it returns a list view over the existing list.

这不会将项目复制到新列表;它返回现有列表的列表视图。