我有一个类SomeClass
使用静态成员 myMap
enter code here
其形式为 HasmMap<String,ArrayList<SomeOtherClass>>
从文件中反序列化。
我有一个方法
public ArrayList<SomeOtherClass> getList(final String key, final int N)
应该查找 key
在 map 中并返回第一个 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
}
}
如何高效地执行此操作,即在实际返回正确数据的同时不在内存中创建不需要的副本?
最佳答案
用 List
s subList
method 创建一个子列表.
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.
从索引 0(包含起始索引)开始,到索引 N
(不包含结束索引)结束。
return arr.subList(0, N);
这不会将项目复制到新列表;它返回现有列表的 ListView 。
关于java - 如何在 Java 中正确返回 ArrayList 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34731034/