Programming to an interface - avoiding the later cast

interface, java

Solution

First of all ask yourself a question: why do you need an `ArrayList`? Furthermore, should the clients of your API care about it? You have few choices:

make `getIntegers()` return `ArrayList<Integer>`. It's not a crime

Consider less strong interface requirement, e.g. `AbstractList` as a consensus

Create a defensive copy so that you can consume any `List`:

ArrayList<Integer> list = new ArrayList<Integer>(getIntegers());

consider using `instanceof` operator to avoid unnecessary copy if `getIntegers()` is already an `ArrayList`.

In other words - there is no way to avoid this casting with your requirements and in elegant way.

Problem

So, as I understand, one should always program to an interface, as in: ``` List<Integer> list = new LinkedList<Integer>(); ``` So, later in my program I have: ``` public List<Integer> getIntegers() { return list; } public void processIntegers() { // I need an arraylist here ArrayList<Integer> list = (ArrayList<Integer>) getIntegers(); // can I do this better, without a cast? } ``` Can I follow a better pattern here or somehow do something to avoid the cast? Casting seems very ugly in this scenario. Thanks.

Original source