How To Access hash maps key when the key is an object

落花浮王杯 提交于 2019-12-23 20:10:17

问题


I cannot seem to figure out how to access the values of my hashmap

What I am basically trying to do is create a hashmap with an array as one of the values like json style.. If that makes sense?

So I want something like hash{key: value1, value2, value3, [number1,number2]}

and be able to access it like (pseudocode:) hash.get(3).get(1)

public class WebSearch {

readFile.ReadFile xfile = new readFile.ReadFile("inputgraph.txt");
HashMap webSearchHash = new HashMap();
ArrayList belongsTo = new ArrayList();
ArrayList keyphrase = new ArrayList();


public WebSearch() {




}


public void createGraph()
{
    HashMap <Object, ArrayList<Integer> > outlinks = new HashMap <Object, ArrayList<Integer>>();
    for (int i = 0; i < xfile.getNumberOfWebpages(); i++ )
    {
        keyphrase.add(i,xfile.getKeyPhrases(i));
        outlinks.put(keyphrase.get(i), xfile.getOutLinks(i));

    }

}

keyphrases is an ArrayList

this is my output of System.out.print(outlinks);

{[education, news, internet]=[0, 3], [power, news]=[1, 4], [computer, internet, device, ipod]=[2], [university, education]=[5]}

How would I go about getting say just this: [education, news, internet]=[0, 3]

I have tried:

outlinks.get(xfile.getKeyPhrases(i))

xfile.getKeyPhrases(0) would for example return [education, news, internet]


回答1:


You can get the key set (Map.keySet()) of the map first; outlinks.keySet()

Then you can use these keys on your map to get your entries (values of the keys)




回答2:


You haven't posted enough of the surrounding code for your question to be entirely clear, but look at the Javadocs for Map. You will probably get what you want by iterating over outlinks.values().




回答3:


I recommend to use a customized object and use it inside your collections.

You may create a POJO/Bean class and overwrite the toString method with the details that you want, for instance the a iterate over items inside a array. When you use it to print or display the toString method will be call.

The following link show you some ideas:

http://www.javapractices.com/topic/TopicAction.do?Id=55

http://en.wikipedia.org/wiki/Plain_Old_Java_Object




回答4:


You can access the keys of any HashMap using Map.keySet() method.

Also note that java.util.HashMap is unordered. HashMap makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

You would like to relook at the structure of your HashMap, you are having ArrayList as your key.



来源:https://stackoverflow.com/questions/17983696/how-to-access-hash-maps-key-when-the-key-is-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!