Let's say we want to have a method in an interface that returns an array, like this:
interface A {
B[] findAllB();
}
But arrays are very low-level and implemented definitively. Their implementation is final and cannot change, much like a final class. It is not possible to return anything else other than an array if the return type in this interface is already an array. So when it is better to avoid having arrays as return types because it restricts the freedom of the implementing class to return whatever it wants to return. So, we decide to use java.util.List
:
interface A {
List<B> findAllB();
}
But when implementing this interface, it might be extremely convenient for us to return an actual array, that in theory, does implement the List interface (e.g. with add
and remove
throwing UnsupportedOperationException
s):
class AImpl implements A {
List<B> findAllB() {
B[] array = ...;
...
return array; // does not work
}
}
But this does not work because you cannot return a B[]
instead of List<B>
.
I was wondering if there is an interface, (or if it even is possible to have an interface) that the low-level Java array implements, or, in other words, it is safe to return an array in its stead.
If this were possible, java.util.List
could also extend it so we can return arrays or lists interchangeably behind the curtains.
I already suspect this is impossible, but in the world of computers anything is possible, so who knows.