Re: Method chaining with generics



Oliver Wong wrote:
"Hemal Pandya" <hemalpandya@xxxxxxxxx> wrote in message news:1125487477.912674.260290@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Chris Uppal wrote:

Raymond DeCampo wrote:


Is there any case
when casting a List to List<Object> would cause a problem?

I haven't been following the thread, so this may be irrelevant. But if you
start with a List that is intended to hold Strings (whether it's declared as a
List or a List<String> doesn't matter provided it reaches your code as a List)
and cast that to a List<Object>, then you'll be able to add a Rectangle to it,
which would not be correct.

Very true. There are two different cases depending on how the List started. If it was intended to hold Strings but created as a List, not a List<String> then the error is at the point of creation. This issue exists in all java until 5.0. If it was created as a List<String> then the error is where it was converted to List.

But given a List, which by definition is a list of Objects, is there a
case where casting it to List<Object> is dangerous?


This is exactly the issue that the compiler is warning about: Due to type erasure, there's no way for the runtime to ensure that something which is a "List" is actually a "List<Object>" and not, for example, a "List<String>".

public static test(List someList) {
  List<Object> listOfObjects = (List<Object>)someList;
}

public static void main(String args[]) {
  test(new List<String>());
}

In the above sample code, the runtime will NOT throw a class cast exception, because it will not be able to detect that the list passed was actually a list of Strings and not a list of Objects.

    Hence the warning in the compiler.


The point we are trying to make is that it makes more sense (IMHO) to emit a warning when casting a List<String> or such to a List. Then the warning on a cast from List to List<Object> could be eliminated and your scenario is still covered by a warning.


Ray

--
XML is the programmer's duct tape.
.


Quantcast