If myPojos
has been declared as an ArrayList<MyPojo>
you cannot just cast it to ArrayList<MyInterface>
and return it. Peter Lawrey has shown how you can ignore the ominous screams of impending doom issued by the compiler when you try to do that, (I would add that his solution is missing a @SuppressWarnings( "unchecked" )
statement,) but it is still a very bad idea to do that.
That's because when you return an ArrayList<MyInterface>
to the caller, then the caller can add an instance of SomeOtherPojo implements MyInterface
into that ArrayList
, resulting in your original ArrayList<MyPojo>
containing a SomeOtherPojo
among the MyPojo
s, which is a disastrous situation known as Heap Pollution (Wikipedia): attempting to iterate all the MyPojo
s in the original ArrayList<MyPojo>
will throw a ClassCastException
.
You might say that in your particular situation you know beyond a shadow of a doubt that none of this will happen, but this is programming by coincidence, and in any case the stackoverflow community has nothing to gain from answers that take into consideration the specifics of your particular situation. So, my advice to you would be to be courteous towards other programmers who might work with your code, follow the principle of least surprise, and do it properly.
You have two options:
- Create your
ArrayList<MyInterface>
and populate it as others have shown.
- Do not return an
ArrayList<MyMyInterface>
; instead, return a List<MyInterface>
which has been created either with Collections.unmodifiableList( myPojos )
or (since Java 10) with List.copyOf( myPojos )
. When a function returns a list, this list should be immutable. ArrayList
is explicitly mutable, so it is unsuitable. Unfortunately, Java does not have an immutable list interface, but most people are accustomed to treating a List<E>
returned by a function as immutable and never attempting to invoke any mutation methods on it. If they do, they will get a runtime error, which will be easy to fix, instead of the owner of myPojos
receiving a completely inexplicable ClassCastException
which is very hard to troubleshoot because it happens at an unknown point in time later.
For an explanation of what List.copyOf()
does, and why it is a very good choice, see https://mcmap.net/q/54704/-most-efficient-way-to-cast-list-lt-subclass-gt-to-list-lt-baseclass-gt