2

How java stores and deals with generic information with references.

List<A> is a subtype of List<?>. Please explain above statement. How inheritance works with references to a generic object.

yshavit
  • 42,327
  • 7
  • 87
  • 124
Babu Reddy H
  • 186
  • 1
  • 11
  • 4
    Possible duplicate of [Java generics - type erasure - when and what happens](http://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens) – stevecross Oct 14 '15 at 06:23

2 Answers2

0

"A is a subtype of B" means that everywhere where type B is necessary, you may use the type A as well. In your statement List<?> type is "list of objects of any type, we don't care about it" and List<A> type is "list of objects of type A". Thus it should be obvious that everywhere we need "list of objects of any type" we can also use "list of objects of type A".

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
0

From Java Docs

The unbounded wildcard type is specified using the wildcard character (?), for example, List. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach:

  1. If you are writing a method that can be implemented using functionality provided in the Object class.
  2. When the code is using methods in the generic class that don't depend on the type parameter.

Moving from unbounded(?) to bounded type() is moving away from Generic to Specific entity.

let's go through my own example.

  1. Earth, a planet have Living Things

  2. Animals, Trees are some of the Living things

  3. Humans are animal with 2 legs and 2 hands

  4. Men & Women are two types of humans.

If you have ? in List, you can apply List to Living things. But if you want your list to contain only Humans or Men or Women, you will decide bounded type as per your need.

As you move from generic to specific : List < ? > , List < Living things >, List < Humans >, List< Men >, you are applying more specific things to your entity.

Tree is a Living thing like Human or Men but it can't have 2 legs and 2 hands like Men and it can't think.

You have to decide at which specific level, you want to bind the entity to specific type.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211