Unchecked conversion warning of List

458 Views Asked by At

When I compile my java code with -Xlint:unchecked, in this line:

            List<HierarchyNode> list = hier.getHierarchyNodesParentFirst(0);

I receive this:

... unchecked conversion
required: java.util.List<ir.ac.ut.iis.person.hierarchy.HierarchyNode>
found:    java.util.List

getHierarchyNodesParentFirst is defined as:

public class Hierarchy<U extends User> {
    ...
    public List<HierarchyNode> getHierarchyNodesParentFirst(int owner) {
        List<HierarchyNode> hierarchyNodesChildFirst = getHierarchyNodesChildFirst(owner);
        ...
        return hierarchyNodesChildFirst;
    }
}

It is not overrided anywhere and it does not override anything. What can the problem be?

1

There are 1 best solutions below

4
On

In the comments you stated that you have defined variable hier as with Hierachy hier = new Hierarchy<>();. This is causing the unchecked warning because you have left out the type variable in the variable declaration. The warning was not caused by the invalid conversion between List and List<HierarchyNode> as one could have initially thought by reading the compiler warnings.

The following for example should do the trick:

Hierarchy<? extends User> hier = new Hierarchy<>();
List<HierarchyNode> list = hier.getHierarchyNodesParentFirst(0);

or alternatively (which probably is not intended)

Hierarchy hier = new Hierarchy<>();
List list = hier.getHierachyNodesParentFirst(0);

Edit: you can also remove the generic parameter <U extends User> from class Hierarchy. Obviously this is not probably what you want, but it emphasises that since there's no type, type erasure cannot occur and the code will compile without warnings.

This is caused by type-erasure. There's some discussion in StackOverflow.