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.
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()returnArrayList<Integer>. It’s not a crimeConsider less strong interface requirement, e.g.
AbstractListas a consensusCreate a defensive copy so that you can consume any
List:consider using
instanceofoperator to avoid unnecessary copy ifgetIntegers()is already anArrayList.In other words – there is no way to avoid this casting with your requirements and in elegant way.