3

from the text "Java Generics and Collections" by Naftalin and Wadler, a passage states that though Integer is a subtype of Number, List<Integer> is not a subtype of List<Number>.

This prevents one from using, polymorphically, references to the in places where one might traditionally expect to allow such statements.

My question here is, since the 'substitution principle' does not apply in the case List<Integer> and List<Number>, does the restriction on the principle relate to where a class and a specific type (assigned for a generic type) are combined - in all cases and in general - (here as 'List<Integer>' for example). Here in this case I refer to the notion of substiution in resepct to a statement like 'List<Integer>', as opposed to 'List', or '<Integer>' seperatley.

Or alternatively, is the restriciton instead defined through some mechanism that specifies whether and which classes are subtypes (and thus when and when it applies) as one does through the usual extends and implements mechanism.

Essentially i do not understand the mechanism through which the susbtitution principle in such cases are caused to be defined as applying or not applying.

many thanks

manOf
  • 53
  • 5
  • 1
    By 'generic substitution principle' do you mean the so-called [Liskov](https://en.wikipedia.org/wiki/Liskov_substitution_principle) substitution principle? Perhaps the concepts you are looking for are [covariance and contravariance](https://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29). – Codor May 06 '16 at 10:59

1 Answers1

1

If I understood the question correctly, in Java and in the situation you described, the Liskov substition principle does not apply because List<Integer> is not a subtype of List<Number>, which however is a requirement for the Likov substition principle.

That being said, the relation between List<Integer> and List<Number> can be described by covaraince and contravariance, which models the expactation which could be formulated as follows.

As Integer is a subtype of Number, which means that every implementation for Number can be used for Integer, the same must apply for types which instantiate the same generic template, but use Integer and Number as type arguments.

However, to my understanding, this is a different mechanism, which is also discussed in this question for generics.

Community
  • 1
  • 1
Codor
  • 17,447
  • 9
  • 29
  • 56
  • 1
    Thank you for your answer, I shall study the links you gave me and im pretty sure from your second paragraph this is exactly what I need! Thank you also for being willing to deal with a rather poorly written question (I appologise, i've been very very much sleep deprived of late). I hugely apprecite you being happy to deal with a question that could be have been writte more clearly! – manOf May 06 '16 at 11:47