M
M
Maks Burkov2017-04-05 13:05:27
Java
Maks Burkov, 2017-04-05 13:05:27

How to properly use HashMap?

When trying to shove data into the hashmap , it turns out to shove only the last object , why ?

@BeforeClass
   public static void createCompanies(){
        System.out.println("Setting companies data! ");
       instances.put("company1",adminServiceTesting.createCompany("ORG","[email protected]",34553453,"[email protected]",callForCompany()));
       instances.put("company2",adminServiceTesting.createCompany("PPP","[email protected]",4536579,"[email protected]",callForCompany()));
   }

Continuation of the topic

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alexandrov, 2017-04-05
@Maks00088

I suspect that the error is not in the above code, but elsewhere. Where are you initializing the hashmap?
The hashmap itself is a key-value pair. Keys must be unique as per the standard or overridden hashCode(). Values ​​may not be unique.
Those. in your situation:

instances = new HashMap<String,CompanyObject>();
//String - ключ, тип строка, функция hashCode() встроенная, можно не переопределять
//CompanyObject - ваш объект с данными, на hashCode() пофиг ибо он использоваться не будет совсем
instance.put("comp1", objectComp1); //будет добавлен
instance.put("comp2", objectComp1); //будет добавлен т.к. хэш ключа будет другим
instance.put("comp1", objectComp6); //оп, коллизия, в позиции "comp1" будет заменено "Значение"(objectComp1) на (objectComp6)

R
ruslanys, 2017-04-13
@ruslanys

In order to use your type as a key in a HashMap, you need to override the equals and hashCode methods.
It is also recommended to make the values ​​involved in the hashCode calculation constants (final).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question