6
I have a Hashmap users:
private Map<String, ObjectOutputStream> utilizadores = new HashMap<String, ObjectOutputStream>();
Can anyone tell me what this function does exactly? Here under no circumstances is Hashmap changed because it does not?
private synchronized void enviar_para_um(Mensagem mensagem){
for(Map.Entry<String, ObjectOutputStream> mapa : utilizadores.entrySet()){
if(mapa.getKey().equals(mensagem.getNomeClienteReceptorMensagem())) {
try {
mapa.getValue().writeObject(mensagem);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I just don’t understand why the developer iterates the
HashMap
instead of doing something likeObjectOutputStream oos = utilizadores.get(mensagem.getNomeClienteReceptorMensagem()); if (oos != null) { oos.writeObject(mensagem) }
. It seems that this bond is unnecessary.– Anthony Accioly
it’s basically going to be the same!
– rrr
Well observed @Anthonyaccioly. The loop is unnecessary in this case. The access is O(1), but in this case is O(n). Anyway, I’ve been following the java, I’ve even talked to him in chat. He’s in the learning process and it looks like this is a graduation project.
– cantoni
@java, really the effect is the same, however, the chunk of code proposed by Anthonyaccioly eliminates the need for the loop. If there were many users, then the loop would be much slower than the chunk of code proposed by it. Note that a hashmap is a data structure built so that you can access the data in time O(1).
– cantoni
@Cantoni the way that Anthony said is most noticeable! however it is all a matter of speed in data processing.
– rrr
@Anthonyaccioly, worth an answer. Your comment enriches the discussion.
– cantoni
Exact @java. In this case, it’s more a question of performance added to a clarity of code. This. :-)
– cantoni
@Anthonyaccioly put your answer here
– rrr
@Cantoni help me on the other issue I put pff
– rrr
Done. And a long sentence for the comment pass.
– Anthony Accioly