-1

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>)

Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113

1 Answers1

1

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;
    }
}
SMA
  • 36,381
  • 8
  • 49
  • 73
  • 1
    LOL, a rather less expensive way of assigning all elements of `parcelables` to `parsedData` is `return parcelables`. – Smutje Oct 17 '14 at 12:13
  • 1
    Yes he could but he might be doing something else within which is hidden from us? – SMA Oct 17 '14 at 12:14
  • 1
    Yes, he casts type `Parcelable` to `T` to continue using a type safe collection. – Smutje Oct 17 '14 at 12:15
  • @Smutje of course you are right. Actually, I had some utility method that was just doing type conversion from List to ArrayList. This utility class and method was not needed at all- I just get rid of it. – Bartosz Bilicki Oct 17 '14 at 12:25