#A question about generics

1 messages · Page 1 of 1 (latest)

somber wind
#

Hi,
I am a java beginner and just reached generics in my course
I am making some notes about generics, and wanted to know if my understanding is correct here. I need to be sure I am not making wrong notes

Also, why would java behave like this? is this a feature , and is this behaviour of generics any helpful to us?

Also what does it mean by invariance?

cursive edgeBOT
#

<@&987246399047479336> please have a look, thanks.

mental bramble
#

so by invariance it means just that a List<String> is not assignable to a List<Object>

hearty sail
#

Generics in java are invariant because it's the only logical option (except declaration site variance). The reason you can't assign a Box<Dog> to Box<Animal> is that then you'd be able to put a Cat in it

mental bramble
#

even though you could assign a String to an Object

#
List<String> strings = ...;
List<Object> objects = strings;
objects.add(123);

strings.get(0); // oh no
hearty sail
#

Arrays are actually covariant (can put String[] as Object[]), but this means you get runtime errors when putting other values in (ArrayStoreException)

#

It was a necessary feature before java got generics, but nowadays it's mostly useless

somber wind
mental bramble
#

there are ways around it

#

like List<? extends Object>

#

but those are a bit unobvious until you've used "normal" generics for a bit

somber wind
#

but why would you not require polymorphism there ?

mental bramble
#

"a list of strings cannot be a list of objects even though a string is an object"

somber wind
#

okay I meant to say why would polymorphims in type parameter would be invalid? is it helpful ?

mental bramble
#

i think you need to clarify whay you mean by polymorphism

#

its invalid because its unsound

#

same as String s = 123; is

zealous badge
#

yes, Java's generics are (unfortunately) invariant

#

So a List<String> is not a List<Object>