Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java force generic types to be cast?

I do not understand why the compiler can not see that a cast is safe when the parameterized type is defined as extending a base class. Here are examples of casts that seem to me like they should be unnecessary. Further, when I do include the cast, my IDE (IntelliJ IDEA) warns that the cast is unchecked, as if to suggest that I am doing something wrong. Is there an idiom that avoids these casts and warnings? Why are the casts needed at all, given that the declaration states that the type extends the base class?

class Shape {}

class Polygon extends Shape {}

public class Foo<T extends Shape>
{
  Set<Polygon> polygons;
  // Why must this be cast?
  Set<T> shapes = (Set<T>) new HashSet<Polygon>(); 

  T getFirst()
  {
    // Why must this be cast?
    return (T) polygons.iterator().next();
  }

  Iterable<T> getShapes()
  {
    // Why must this be cast?
    return (Iterable<T>) polygons;
  }
}
like image 233
Paul Jackson Avatar asked Jun 16 '26 14:06

Paul Jackson


1 Answers

Let's assume you've instantiated your class like this:

Foo<Circle> circleFoo = new Foo<Circle>( );

Then, Set<Circle> cannot be safely assigned HashSet<Polygon>

In getFirst: You cannot safely cast Polygon to Circle

And in getShapes: you cannot safely cast Iterable<Polygon> to Iterable<Circle>.

like image 146
Alexander Pogrebnyak Avatar answered Jun 18 '26 02:06

Alexander Pogrebnyak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!