Search code examples
javaclasshashmap

Trying to put classes in hashmap but its not working


So i have input like this:

 [1]     name1 + type1 + value1
 [X]     nameX + typeX + valueX

now i am looking at input like this:

 [2]     name1 + type2 + value2

so [2] has same name as [1] but their properites are different.

i put the name,type,value in a class like this:

 class entity(){

 String name;
 String type;
 int amount;
 //constructor ... etc...
 ...
 }

what i want to do is put entity into a hashmap with the key being the name and the value being the class entity.

like this

  name1 ----> entity1
  nameX -----> entityX

the problem i am having is when i try to put [2] into the hashmap it has the same name as [1] so it doesnt hash properly ([2] overrides [1] since they have the same name.

i will need to later access [1] and [2] by their name when i search for it.. how would i enter it into the map so it wont override it.


Solution

  • 1 - You need to modify your class entity like below :-

     class entity(){
    
     String name;
     ArrayList <String> type;
     ArrayList <Integer> amount;
     //constructor ... etc...
     ...
     }
    

    2 - Now when ever you are going to enter any value in hashmap, First check that is that key is available in map. If key is available in map, fetch that value associated to that key and enter your new type and amount value in arraylist.

    if(hashmap.contains(nameX)){
        entity obj = hashmap.get(nameX);
        type.add(new_val);
        amount.add(new_val);
        hashmap.put(nameX,obj);
    }
    else{
        entity obj = new entity();
        type.add(new_val);
        amount.add(new_val);
        hashmap.put(nameX,obj);
    }
    

    Note:- change your class name from entity to Entity. its standards code pratice.