5 ms·
In Java, Cat[] can be passed to a function expecting Animal[]. List<Cat> can't be passed to someone expecting List<Animal>. The first case is allowed by the la
by tsimionescu 7y ago
In Java, Cat[] can be passed to a function expecting Animal[]. List<Cat> can't be passed to someone expecting List<Animal>.
The first case is allowed by the language, but it is not type-safe - depending on your usage, you may get type errors at runtime (trying to write a Dog to an Animal[] that is actually a Cat[]).
Java does also support a safe way of achieving variance - your function can take a List<? extends Animal>, in which case you can pass a List<Cat> to it. The compiler also makes sure that a function that takes a List<? extends Animal> can't write a Dog to that list, so this is actually type safe.