Interface Programming - Avoiding Later Translation

So, as I understand it, you always need to program the interface, as in:

List<Integer> list = new LinkedList<Integer>(); 

So, later in my program, I:

 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 the best pattern here or somehow do something to avoid the cast? Casting seems very ugly in this scenario.

Thanks.

+6
source share
1 answer

First of all, ask yourself the question: why do you need an ArrayList ? Also, should your API clients take care of this? You have few options:

  • do getIntegers() return ArrayList<Integer> . This is not a crime.

  • Consider less stringent interface requirements, for example. AbstractList as a consensus

  • Create a protective copy so you can use any List :

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

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

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

+7
source

Source: https://habr.com/ru/post/921001/


All Articles