1

I have a class Message and a list of message : List<Message> messages

I cannot do List<Object> objects = messages; I know that.

But I can do this without compilation errors :

Object object = messages;
List<Object> myList = (List<Object>) object;
myList.add(new Object());

Then my messages list can contain any object and not just Message objects. Why is that ?

5
  • it is the myList list which contains any object. messages has no longer anything to do with it. Commented Sep 3, 2019 at 13:49
  • sure but myList and messages are referencing the same object on the heap (an instance of List<Message>). In that case why "List<Object> objects = messages" is forbidden ?? Commented Sep 3, 2019 at 13:51
  • @robingood If he cast a List<Message> to a List<Object>, it's still the same object. Commented Sep 3, 2019 at 13:51
  • 3
    Java generics are there to help you avoid mistakes. When you cast around them, you bypass the checks that are there to prevent this. Commented Sep 3, 2019 at 13:52
  • 3
    Without compilation errors, yes. But not without compiler warnings. Turn on all compiler warnings, and pay attention to them. The compiler will tell you that your cast is unsafe. (You can even use -Werror to make the compiler treat them as errors.) Commented Sep 3, 2019 at 16:08

1 Answer 1

1

Casting messages to a List<Object> will make your essential Message instances be treated like Object instances and nothing more (at Runtime).

Additionally, you can somewhere cast these Objects back to Message, but the compiler cannot give any guarantees that you won't get a ClassCastException at Runtime (because it could be that you pick the new Object() instance and try to cast it to Message)

That's actually the reason why myList.add(new Object()) compiles - the compiler doesn't complain, because that added instance conforms the content definition of myList.

Not related to your question problem, but probably worth mentioning is that the casting operation is actually highly discouraged, as it's an indicator of a poor object design.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.