In this article, we’ll learn about generics in Java, with an emphasis on the concept of variance.

Substitution of Values

Let’s start by introducing types and subtypes. Java supports assigning a subclass value to a variable of a base type. This is known as a widening reference assignment. We can therefore say that a Float is a subtype of a Number:

Float myFloat = Float.valueOf(3.14f);
Number number = myFloat;

Arrays are covariant and reified

Variance tells us what happens to this subtyping relationship when the original types are placed in the context of another type.

Let’s take arrays, for example. We can ask, since Float is a subtype of a Number, what can we say about an array of Floats relative to an array of Numbers?

It turns out that in Java, arrays are c…

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help