How to solve "Type mismatch: can not convert from object type to Message"?

0

I was studying JSF and found this site where it teaches to create a basic chat using JSF, primefaces and ajax: link

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;
    }

}

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

The first error is to cast cast , so I did and the error disappeared, but the second error ( for(Message m : messages) { ) points to the following message:

  

Type mismatch: can not convert from object type Object to Message

How can I resolve this error?

    
asked by anonymous 18.02.2016 / 21:41

1 answer

1

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

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

then the JVM can not guarantee that Object is an instance of Message . To solve this, you just need to change the declaration to

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

Another alternative is to actually loop the loop with a Object , but give cast to Message soon after:

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