Re: Generics warning message.



You are absolutely correct: it is a copy not a cast. I believe that
because of the nature of type erasure <http://java.sun.com/docs/books/
tutorial/java/generics/erasure.html> it is impossible to do a cast
(without at least generating a warning). Thus to achieve the effect
that the OP desires, it is necessary to cheat (e.g. copying rather
than casting).

If I may rephrase your answer here with a bit of code; if we had a write method doing something like:

ObjectOutputStream out=...
ArrayList<FooBar> objs=new ArrayList<FooBar>();
objs.add(new FooBar());
out.writeObject(objs);

And later we read that back as:

ObjectInputStream in=...
ArrayList<AppToWatch> objs=(ArrayList<AppToWatch>) in.readObject();

Then the cast would succeed, but iterating through the list after it had been read would throw spurious ClassCastExceptions (hence the warning).


If you have control of the writing operation as well as the reading,
then you could solve this problem by using a nonparameterized
extension of ArrayList<R>. For example, consider class MyArrayList
extends ArrayList<String> { }. If you wrote a MyArrayList, then you
should be able to read it and cast it without warnings.


Reading each object individually is a good solution, as it causes you to validate each object by casting it. Having a implementation with a fixed type works too: it makes one *wish* Collections.checkedList would return a public type, so you could ensure that

CheckedList.getCheckedType()==AppToWatch.class

But, the easiest solution to remove the warning is probably to decorate the read method with

@SuppressWarnings("unchecked")

Obviously, this works when you can safely say that the content of the input stream only comes from well known and trusted write methods (as it is not verifying the contents of the list for type accuracy).

HTH,

-Zig
.



Relevant Pages