我在这里提出的问题的后续:How To Access hash maps key when the key is an object
我想尝试一下这样的东西:webSearchHash.put(xfile.getPageTitle(i),outlinks.put(keyphrase.get(i), xfile.getOutLinks(i)));
不知道为什么我的钥匙是null的
下面是我的代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import readFile.*;
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));
webSearchHash.put(xfile.getPageTitle(i),outlinks.put(keyphrase.get(i), xfile.getOutLinks(i)));
}
}
}当我执行System.out.print(webSearchHash);时,输出是{Star-Ledger=null, Apple=null, Microsoft=null, Intel=null, Rutgers=null, Targum=null, Wikipedia=null, New York Times=null}
然而,System.out.print(outlinks);给了我:{[education, news, internet]=[0, 3], [power, news]=[1, 4], [computer, internet, device, ipod]=[2]}基本上我想要一个哈希图作为我的键的值
发布于 2013-08-01 11:57:46
您确实不应该使用HashMap (或任何可变对象)作为键,因为它会破坏Map的稳定性。根据您打算完成的任务,可能有许多有用的方法和库,但是使用不稳定的对象作为Map键是很麻烦的。
发布于 2013-08-01 12:13:08
所以我想我只需要这样做就可以得到我想要的东西:
for (int i = 0; i < xfile.getNumberOfWebpages(); i++ )
{
HashMap <Object, ArrayList<Integer> > outlinks = new HashMap <Object, ArrayList<Integer>>();
keyphrase.add(i,xfile.getKeyPhrases(i));
outlinks.put(keyphrase.get(i), xfile.getOutLinks(i));
webSearchHash.put(xfile.getPageTitle(i), outlinks);
}发布于 2013-08-01 12:18:45
您的问题是您在此语句中放入了null
webSearchHash.put(xfile.getPageTitle(i),outlinks.put(keyphrase.get(i), xfile.getOutLinks(i)));让我们把它分解一下。put的形式为
map.put(key,value)所以你的密钥是getPageTitle(i)。这很好。
对于您的值,返回值为
outlinks.put(keyphrase.get(i), xfile.getOutLinks(i))根据javadoc,hashmap put返回与此键关联的前一个值(在本例中为keyphrase.get(i)),如果之前没有任何值与其关联,则返回null。
由于之前没有任何内容与您的键相关联,因此它返回null。
所以你的陈述实际上是在说
webSearchHash.put(xfile.getPageTitle(i),null);http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html#put(K
https://stackoverflow.com/questions/17984901
复制相似问题