Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming to an interface - avoiding the later cast

Tags:

java

interface

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.

like image 419
jn1kk Avatar asked Jul 20 '12 21:07

jn1kk


1 Answers

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.

like image 52
Tomasz Nurkiewicz Avatar answered Nov 06 '22 22:11

Tomasz Nurkiewicz