Search code examples
javagenericsbounded-wildcardpecs

How to remove 'unchecked' warning from my method?


I have following code

private static class ParcelableParser<T> {
    private ArrayList<T> parse(List<Parcelable> parcelables) {
        ArrayList<T> parsedData = new ArrayList<T>();
        for(Parcelable parcelable : parcelables) {              
            parsedData.add((T) parcelable);
        }
        return parsedData;
    }
}

It is called as follows

ParcelableParser<SomeClass> cellParser = new ParcelableParser<SomeClass>();
cellParser.parse(bundle.getParcelableArrayList("some String"));

It gives warning Type safety: Unchecked cast from Parcelable to T.

No matter what I do, I always have some nasty compilation error. I have read about PECS rule, but I am not able to apply it here.

sample solution (does not compile)

private static class ParcelableParser<T extends Parcelable> {
    private ArrayList<T> parse(List<T> parcelables) {
        ArrayList<T> parsedData = new ArrayList<T>();
        for(T parcelable : parcelables) {               
            parsedData.add((T) parcelable);
        }
        return parsedData;
    }
}

Using it as

return new ParcelableParser<SomeClass>()

.parse(bundle.getParcelableArrayList("SomeString"));

prodces

The method parse(List<SomeClass>) in the type MyClass.ParcelableParser<SomeClass> is not applicable for the arguments (ArrayList<Parcelable>)


Solution

  • As you know parcelable is of type T why don't you use T instead. Try this:

    public static class ParcelableParser<T> {
        private ArrayList<T> parse(List<T> parcelables) {
            ArrayList<T> parsedData = new ArrayList<T>();
            for(T parcelable : parcelables) {              
                parsedData.add(parcelable);
            }
            return parsedData;
        }
    }