如何在 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
How to properly return part of ArrayList in Java?
提问by I Z
I have a class SomeClass
with a static member myMap
enter code here
that has the form HasmMap<String,ArrayList<SomeOtherClass>>
which gets de-serialized from a file.
我有一个SomeClass
带有静态成员的类,该成员myMap
enter 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 key
in the map and return the first N
elements of the corresponding ArrayList
, or the whole thing if the list has <= N
elements. How should I implement the TODO
line 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 List
s subList
method.
使用List
ssubList
方法创建一个子列表。
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.
这不会将项目复制到新列表;它返回现有列表的列表视图。
回答by Jacob Young
return arr.subList(0, N);
The documentation is your friend.
文档是您的朋友。
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int,%20int)
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int,%20int)