Doubt interpretation function

6

I have a HashMap users:

private Map<String, ObjectOutputStream> utilizadores = new HashMap<String, ObjectOutputStream>();  

Can anyone tell me what this function works for? Here, under no circumstances does Hashmap change?

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();
                }
            }
        }
}
    
asked by anonymous 13.12.2015 / 21:04

2 answers

4

Turning my comments into an answer.

The code in question is a kind of Dispatcher Pattern . The idea is to send the message by typing it in ObjectOutputStream of given client (according to mensagem.getNomeClienteReceptorMensagem() ).

To improve performance I would rewrite this method as follows:

private synchronized void enviaParaIm(Mensagem mensagem){
    ObjectOutputStream oos = utilizadores.get(mensagem.getNomeClienteReceptorMensagem());
    if (oos != null) {
        try {
            oos.writeObject(mensagem);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Notice that this way the code gets cleaner. In addition there is a performance improvement. The initial method would iterate all map values (linear time O (n) ), while the second method does a direct lookup, which for a HashMap amortized constant time ( O (1) ).

    
14.12.2015 / 11:12
5

The for below will span all HashMap users. To traverse it calls the entrySet() method that returns a Set<Map.Entry<K,V>> .

for(Map.Entry<String, ObjectOutputStream> mapa : utilizadores.entrySet())

The if below checks whether the HashMap item key is equal to mensagem.getNomeClienteReceptorMensagem() .

if(mapa.getKey().equals(mensagem.getNomeClienteReceptorMensagem())) {

If so, then the value of the map is accessed by calling the writeObject method and passing mensagem as a parameter.

mapa.getValue().writeObject(mensagem);

I understand, therefore, that this method does the proposed, that is, it sends the message to a user only. The user where the nomeClienteReceptorMensagem attribute of mensagem passed as parameter matches one of the% co_hash keys%.

    
13.12.2015 / 21:36