Search code examples
javacastingarraylistclasscastexceptiontoarray

Cast to an array of Message


Good Afternoon in my timezone.

I have a "simple" question.

I have an ArrayList , but when i transform this ArrayList to array using the method toArray from the ArrayList object and cast it to Message[] it throws an java.lang.ClassCastException ? The Message class belongs to package "javax.mail.Message" Snippet of code :

 List<Message> messageList = new ArrayList<Message>();
    --code to fullfill the List
   (Message[]) messageList.toArray();

Throws and exception: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljavax.mail.Message;

Can anyone explain me why this happen ?

With the best regards


Solution

  • You should create an array of Message and then pass it to the toArray(). The method you are calling does return an array of Object, hence the classcast exception. You cannot cast an array of one object type to an array of another, even if the second object extends the first.

    Message[] messages = new Message[messageList.size()];
    messageList.toArray(messages);
    

    Check the documentation here