遍历输出自定义类做参数的hash地图有关问题
遍历输出自定义类做参数的hashmap问题
我自定义了一个类,并且也重载了hascode()
然后我想遍历并输出这个hashmap
返回的key的类型应该是StructWord,但是写StructWord就报错,而且最后也无法返回key.unlistedword,一写就报错。那我想要遍历输出StructWord结构中的unlistedword,要怎么写呢?
------解决方案--------------------
首先,你应该要 重写(override) 那个方法叫hashCode()而不是 重载(overload)
然后要override equals(Object o)这个方法才算完成.
为什么你除了Map定义是有泛型其他都没泛型?你应该这样写:
HashMap<StructWord,Integer> temp=new HashMap<StructWord,Integer>();
temp.put(new StructWord("e","gh"), 1);
temp.put(new StructWord("c","cd"), 1);
temp.put(new StructWord("b","cd"), 1);
temp.put(new StructWord("d","of"), 1);
Iterator<Entry<StructWord,Integer>> ite = temp.entrySet().iterator(); //这里要加泛型啊
while(ite.hasNext()){
Map.Entry<StructWord,Integer> entry = ite.next();
StructWord key=entry.getKey();
System.out.println( key.unlistedword);
}
------解决方案--------------------
楼主不细心?你C没大写。
其次2楼说的对
我自定义了一个类,并且也重载了hascode()
public class StructWord {
public String unlistedword;
public String notstopword;
StructWord(String word1,String word2){
unlistedword=word1;
notstopword=word2;
}
public int hascode(){
return unlistedword.hashCode()+notstopword.hashCode();
}
}
然后我想遍历并输出这个hashmap
HashMap<StructWord,Integer> temp=new HashMap<StructWord,Integer>();
temp.put(new StructWord("e","gh"), 1);
temp.put(new StructWord("c","cd"), 1);
temp.put(new StructWord("b","cd"), 1);
temp.put(new StructWord("d","of"), 1);
Iterator ite = temp.entrySet().iterator();
while(ite.hasNext()){
Map.Entry entry = (Map.Entry) ite.next();
Object key=entry.getKey();
System.out.println(key.tostring());
}
返回的key的类型应该是StructWord,但是写StructWord就报错,而且最后也无法返回key.unlistedword,一写就报错。那我想要遍历输出StructWord结构中的unlistedword,要怎么写呢?
------解决方案--------------------
首先,你应该要 重写(override) 那个方法叫hashCode()而不是 重载(overload)
然后要override equals(Object o)这个方法才算完成.
为什么你除了Map定义是有泛型其他都没泛型?你应该这样写:
HashMap<StructWord,Integer> temp=new HashMap<StructWord,Integer>();
temp.put(new StructWord("e","gh"), 1);
temp.put(new StructWord("c","cd"), 1);
temp.put(new StructWord("b","cd"), 1);
temp.put(new StructWord("d","of"), 1);
Iterator<Entry<StructWord,Integer>> ite = temp.entrySet().iterator(); //这里要加泛型啊
while(ite.hasNext()){
Map.Entry<StructWord,Integer> entry = ite.next();
StructWord key=entry.getKey();
System.out.println( key.unlistedword);
}
------解决方案--------------------
楼主不细心?你C没大写。
public int hascode(){
return unlistedword.hashCode()+notstopword.hashCode();
}
其次2楼说的对
Iterator<Entry<StructWord,Integer>> ite = temp.entrySet().iterator(); //这里不加泛型迭代器遍历出来的又是Object类的了。