Do I really need to implement it myself?
private void shrinkListTo(ArrayList list, int newSize) {
for (int i = list.size() - 1; i >= newSi
There is another consideration. You might want to shy away from using an ArrayList in your method signature, and instead work to the List interface, as it ties you into theArrayList implementation, making changes down the line difficult if you find that, for example, a LinkedList is more suitable to your needs. Preventing this tight coupling does come at a cost.
An alternative approach could look like this:
private void shrinkListTo(List list, int newSize) {
list.retainAll(list.subList(0, newSize);
}
Unfortunately, the List.retainAll() method is optional for subclasses to implement, so you would need to catch an UnsupportedOperationException, and then do something else.
private void shrinkListTo(List list, int newSize) {
try {
list.retainAll(list.subList(0, newSize);
} catch (UnspportedOperationException e) {
//perhaps log that your using your catch block's version.
for (int i = list.size() - 1; i >= newSize; --i)
list.remove(i);
}
}
}
That is not as straight forward as your orginal. If you are not tied to the instance of the List that you are passing in, you could just as easily return a new instance by calling subList(int start, int end), and you wouldnt even need to make a method. This would also be a faster implementation, as (in Java 6), you would be getting an instance of an AbstractList.SubList that contains your list, an offset into it and a size. There would be no need for iterating.
If you are interested in the arguments for coding to Interfaces instead of classes, see this favorite article by Allen Holub