16

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?

I Z
  • 5,719
  • 19
  • 53
  • 100

2 Answers2

31

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.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I am getting `java.util.ArrayList$SubList cannot be cast to java.util.ArrayList`. I can replace `return arr.subList(0, N);` with `return new ArrayList arr.subList(0, N);` but then I would be creating a copy, right? – I Z Jan 11 '16 at 21:22
  • That's because the `List` returned by `subList` isn't an `ArrayList`. You can have your method return a `List` instead of an `ArrayList`. Alternatively, you can create an `ArrayList` from the sublist and return it, but that would involve copying. – rgettman Jan 11 '16 at 21:24
  • @rgettman So it's not really that great a solution since he wanted an `ArrayList`. – Hasen Jul 27 '22 at 11:02
  • @Hasen Creating a new `ArrayList` would be inefficient because it involves copying object references to it. – rgettman Jul 27 '22 at 16:59
  • @rgettman Inefficient or not, a `List` is not the same as an `ArrayList`, which is what was asked for. – Hasen Jul 28 '22 at 20:05
  • @Hasen If you have a solution that can create the required `ArrayList` efficiently, without copying, then please post your answer. – rgettman Jul 28 '22 at 20:28
  • @rgettman Yes I have a solution - you can't do it. Sometimes that's the correct answer. If you order some oranges from a supermarket, they don't give you potatoes instead, they just say they're out of stock. – Hasen Jul 30 '22 at 11:14
5
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)

Jacob Young
  • 107
  • 4