开发者

How to store multiple values in hashmap with respect to unique keys

开发者 https://www.devze.com 2023-03-13 06:38 出处:网络
Hi i have to validate the database values with the U开发者_如何转开发I displayed values so I am using Watij as an automation tool.

Hi i have to validate the database values with the U开发者_如何转开发I displayed values so I am using Watij as an automation tool. The problem arises when i have to store the database values into the hashmap. Suppose the database is having 3 fields Name, Email and Address. And after firing the query the fetched rows are 10. I am taking the field values as the Key in hashmap and the retrieved rows as the values.

I am unable to store the values in hashmap. When i used the hashmap the values got overridden and at last i always got the single values for the respective keys. I tried declaring the hashmap having two parameters as string and an string[] but i was unable to read the final values. Can anybody help as i am not a java expert. Thanks.


Where have you declared the string? You will have to declare it inside the loop(where you loop through your resultset). If you are not creating a new object inside the loop, the reference of the same string would be stored in all the values of the hashmap and you would get a single value in your hashmap. If the code was also mentioned here, it would be easy to pinpoint the exact problem.


when storing object in hashmap, you can use the hashcode of that object as key and then can save the object itself as the value, but make sure that you implement hasCode() and equals method properly, as u know, hashmap internally used hashcode() and 'equals` method for storing data.

Now when implementing hashcode or equals method, you can use any attribute (column of that row), which u think, that uniquely identify that row.

And moreover, performance wise this will be a better approach.


You can make a map like as HashMap<String, Data> where the first argument is the key (I suppose a String, you can use what you want) and Data is a a class that contains the data values for the key. Data may be:

public class Data {

    private String name;
    private String address;
    private String email;

    ...
}

You can add object to the map with map.put(key, new Data(...)). A more simple way is use array, in a map like HashMap<String,String[]>, but is not very useful. The Java idea with DB query is to create object to encapsulate every record.


Well in a map, the keys need to be unique, so if you keep add (email,blabla@hotmail.com) and it already had (email,nana@gmail.com) they you would just override the first one. If what you want is just a list of emails, adresses and names wouldn't it be better to make a class called person or something and add those to a list?

Like person(name,email,adress) then add that to a list.

0

精彩评论

暂无评论...
验证码 换一张
取 消