How to set the key and value of an object by creating an instance and putting the values in the map?

0

I only know how to do the hashmap in a way that is creating an instance in the put method to do insertion of values.

Here's how I can do it:

import java.util.Map;

public class Teste {

public static void main(String[] args){

//Exemplo com utilização de hashmap

    Map<Pessoa, Pessoa> example = new HashMap<Pessoa, Pessoa>();



    example.put(new Pessoa(12), new Pessoa("Aline"));
    example.put(new Pessoa(13), new Pessoa("Carla"));

    int key = 2;

    if(example.containsKey(key)){
        System.out.println("Valor é:" + key + " = " + example.get(key));

    }else{
        System.out.println("Não existe!");
    }
  }
}

But I could not do it that way? example:

import java.util.Map;

public class Teste {

    public static void main(String[] args){



    //Exemplo com utilização de hashmap

        Map<Pessoa, Pessoa> example = new HashMap<Pessoa, Pessoa>();

        Pessoa pessoa;

        pessoa = new Pessoa();
        pessoa.setId(40);
        pessoa.setNome("Aline");

        example.put(pessoa.getId(), pessoa.getNome());

        int key = 2;

        if(example.containsKey(key)){
            System.out.println("Valor é:" + key + " = " + example.get(key));

        }else{
            System.out.println("Não existe!");
        }
    }




Class Pessoa:

package ibm;

public class Pessoa {
private Integer id;
private String nome;

Pessoa(Integer num){
 this.id    = num;
}

Pessoa(String nome){
    this.nome = nome;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

}

    
asked by anonymous 28.06.2016 / 15:03

1 answer

3

Your Map key and value types do not match what you're trying to insert into it.

Map is a type of collection that stores keys and values, in order to find a value through its key. In case you want the key to be an integer (id) and the value is the name of the person (String). So your Map should reflect that. In other words ...

This line:

Map<Pessoa, Pessoa> example = new HashMap<Pessoa, Pessoa>();

should be replaced by:

Map<Integer, String> example = new HashMap<Integer, String>();

or better yet, by:

Map<Integer, String> example = new HashMap<>();

UPDATE: Thinking better, you might want to do a little different and locate a Person through your id. In this case you should declare your Map like this:

Map<Integer, Pessoa> example = new HashMap<>();

and change your put() like this:

example.put(pessoa.getId(), pessoa);

Once you've done this, you can see what the person's name is:

Pessoa pessoa = example.get(id);
System.out.println("Nome: " + pessoa.getNome());
    
28.06.2016 / 15:12