3 ms·
The last part makes sense, no? If you could do List<Fruit> fruits = apples Then you could add an orange to the fruits list, and it would appear among the appl
by thomasahle 11y ago
The last part makes sense, no?
If you could do
List<Fruit> fruits = apples
Then you could add an orange to the fruits list, and it would appear among the apples.
It doesn't seem like you can fix this without immutability?
- deleted 11y ago[deleted]
- catnaroek 11y agoThe problem with what Java calls a `List` is that it really isn't a list. It's a mutable cell, whose contents at any given point in time is a list. The methods of the mutable cell let you replace the list with a new one, which happens to be partially based on the old one. Also, because Java's data structures are usually ephemeral, the new list can be created in the same place where the old list was. A type constructor of lists (which Java's standard library doesn't have to the best of my knowledge) is covariant on its element type, but a type constructor of mutable cells is invariant on its content type.
- ohnomrbill 11y agoIf you really did have a case where your list is a list of apples, wouldn't you type: List<Apple> apples = aps If you're using a general type Fruit, and can't stand any fruit that isn't an apple, you probably need to use the more specific Apple type.
- thomasahle 11y agoI mean, the problem of assigning `fruits = aps` is not that you get apples in your fruit list, but that now elements added to fruit (not of apple type) also get added to `aps`. The assignment sort of goes both ways like that.
- ohnomrbill 11y agoAh, your point makes more sense now. Immutability would help a lot here, it seems.