How to resolve "Type Mismatch: cannot Convert from element type Object to Message"?

Asked

Viewed 930 times

0

I was studying JSF and found this site where teaches to create a basic chat using JSF, primefaces and ajax: https://jetcracker.wordpress.com/2012/03/04/jsf-how-to-create-a-chat-with-ajax/

I have the Messagemanager class

public class MessageManager implements MessageManagerLocal {

    private final List messages =
            Collections.synchronizedList(new LinkedList());;

    @Override
    public void sendMessage(Message msg) {
        messages.add(msg);
        msg.setDateSent(new Date());
    }

    @Override
    public Message getFirstAfter(Date after) {
        if(messages.isEmpty())
            return null;
        if(after == null)
            return messages.get(0);
        for(Message m : messages) {
            if(m.getDateSent().after(after))
                return m;
        }
        return null;
    }

}

But an error occurs on this line return messages.get(0); and in this for(Message m : messages) {.

The first mistake tells to make one cast, then I did and the mistake was gone, but the second mistake (for(Message m : messages) {) he points out the following message:

Type Mismatch: cannot Convert from element type Object to Message

How can I fix this mistake?

1 answer

1


The problem in this case is that you do not specify what type of object exists in the LinkedList in

private final List messages = Collections.synchronizedList(new LinkedList());

then the JVM has no way of ensuring that Object is an instance of a Message. To resolve this, you just need to change the statement to

private final LinkedList<Message> messages = Collections.synchronizedList(new LinkedList<Message>());

Another alternative is to actually run the loop with a Object, but cast for Message right away:

for(Object o : messages) {
    Message m = (Message) o;
    if(m.getDateSent().after(after))
        return m;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.