0
I only know how to hashmap in a way that is creating an instance in the put method to insert values.
Follow the way I do:
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 couldn’t do it that way as you do it? 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;
}
}
If name is string and id is int, why didn’t you declare
HashMap<String, Integer>()
instead of using Person? It’s unclear what you’re trying to do.– user28595
When you create a new class you are allocating a pointer to the data, maybe you want to make a map<int, Person>. It really wasn’t very clear the question
– user3010128
I just want to do the implementation in a way that doesn’t need to create an instance. I want to take values already defined in an object and insert.
– Aline