0

I have two classes: superclass Cluster and subclass XCluster. XCluster extends Cluster.

I have this method signature:

public Map<Integer, XCluster> getClusters() {
...
}

I have this variable:

Map<Integer, Cluster> clusters = getClusters();

I can't compile this. Eclipse says that the method getCluster() doesn't return this kind of type. That I need to change the type from XCluster to Cluster.

What's wrong?

Jack Twain
  • 6,273
  • 15
  • 67
  • 107
  • 1
    Similar question a few minutes ago. Here: http://stackoverflow.com/questions/18513990/why-is-it-not-possible-to-call-listnumber-not-with-listinteger-even-intege – Sotirios Delimanolis Aug 29 '13 at 15:02

5 Answers5

5

You can't because: generics in Java are not polymorphic

Your main options (there are others):

  • change the second code to

    Map<Integer, ? extends  Cluster> clusters = getClusters();
    
  • change the method signature to:

    public Map<Integer, Cluster> getClusters() {}
    

Which to use depends on your use case.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
3

Consider what would happen if you tried to insert a Cluster into clusters. Since the result of getClusters() can only hold XClusters, there should be an error. You are correct, however, that if any value you retrieve from the map would be a Cluster, so you could do, for instance,

Cluster cluster = getClusters().get( 0 );
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
2

because a Map<Integer, XCluster> is not a Map<Integer, Cluster>. Generics does not work this way with polymorphism. You can read about Polymorphism with generics and this question

Community
  • 1
  • 1
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
1

Java generics won't allow you to do that. An object of type Map<Integer, XCluster> is not the same as an object of type Map<Integer, Cluster>, even if XCluster extends or implements Cluster, as explained here: Generics, Inheritance, and Subtypes.

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
0

Java cannot decide that values column contains a superclass. It will not check at that granular level.

Lokesh
  • 7,810
  • 6
  • 48
  • 78