0

I have a Java class that acts as a container of another generic class. It stores the objects of the generic class in a vector. For reasons too complicated to get into, mostly related to obsessive refactoring (thanks Gil), the class contains a method that does nothing but add an element to the vector. So in summary I have something like this:

public abstract class DataElementArray<E extends DataElement>
extends ComplexDataElement
implements DataElement, Iterable<E>
{
    private Vector<E> m_vMembers ;

    @Override
    public abstract DataElementArray<E> addChild( DataElement de ) ;
    // This method is expected to make use of the following utility method:

    @Override
    protected DataElementArray<E> addChildToVector( DataElement de )
    {
        m_vMembers.add( (E)de ) ;
        return this ;
    }

    // other stuff ...
}

On that line that does the typecasting from DataElement to E, Eclipse gives me the following warning:

Type safety: Unchecked cast from DataElement to E

I wouldn't think that this would be a problem, because it's already defined at the top of the class that E extends DataThing.

Short of using the @SuppressWarnings annotation to shut up the Eclipse hint service (which it suggested itself, strangely enough), what more can I do to alleviate this warning? Should I bother enclosing this line in a try {} catch(ClassCastException) block, even though I know that the source class will always be castable into the target?

zerobandwidth
  • 1,213
  • 11
  • 18

1 Answers1

0

You can't and shouldn't get rid of this warning when you're casting to E here. The source class, DataElement, may not always be cast-able to the target E. You can't cast to E, because E could be a subclass of DataElement, and a downcast here is completely inappropriate.

The easiest way to fix this is to make the parameter de of type E, but given that this method seems to override something in the superclass ComplexDataElement, the superclass method needs to take an E also. That would mean that ComplexDataElement should be generic with something like <E extends DataElement> also.

rgettman
  • 176,041
  • 30
  • 275
  • 357