How to properly return part of ArrayList in Java?

I Z picture I Z · Jan 11, 2016 · Viewed 14.5k times · Source

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

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:

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?

Answer

rgettman picture rgettman · Jan 11, 2016

Create a sublist with Lists 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.

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

return arr.subList(0, N);

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