在Java中打印HashMap [英] Printing HashMap In Java
问题描述
我有一个HashMap:
private HashMap< TypeKey,TypeValue> example = new HashMap< TypeKey,TypeValue>();
现在我想运行所有的值并打印它们。
我这样写:
for(TypeValue name:this.example.keySet()){
System.out.println(name);
}
似乎不起作用。
有什么问题?
编辑:
另一个问题: /download.oracle.com/javase/6/docs/api/java/util/HashMap.html#keySet%28%29> keySet()只返回一组key在你的hashmap,你应该迭代
在你的示例中,hashmap键的类型是 TypeKey
,但是在您的通用for循环中指定了 TypeValue
,因此无法编译。您应该将其更改为:
for(TypeKey name:example.keySet()){
String key = name.toString();
String value = example.get(name).toString();
System.out.println(key ++ value);
}
如果您不需要打印
另一个问题:这个集合
是零吗?基础?我的意思是如果它有1个键
,值将是0或1?
c $ c> keySet()是一个设置< /a>。您无法使用索引从集合中获取值,因此不是基于零或基于一的问题。如果您的hashmap有一个键,返回的keySet()将在其中有一个条目,其大小为1.
I have a HashMap:
private HashMap<TypeKey,TypeValue > example= new HashMap<TypeKey, TypeValue>();
Now I would Like to run through all the values and print them.
I wrote this:
for (TypeValue name: this.example.keySet()){
System.out.println(name);
}
It doesn't seem to work.
What is the problem?
EDIT: Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?
keySet() only returns a set of key in your hashmap , you should iterate this key set and the get the value from the hashmap using these keys .
In your example , the type of the hashmap 's key is TypeKey
, but you specified TypeValue
in your generic for-loop , so it cannot be compiled. You should change it to :
for (TypeKey name: example.keySet()){
String key =name.toString();
String value = example.get(name).toString();
System.out.println(key + " " + value);
}
If you don't require to print key value and just need the hashmap value , you can use others' suggestion .
Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?
The collection returned from keySet()
is a Set.You cannot get the value from a Set using an index , so it is not an question whether it is zero-based or one-based. If your hashmap has one key , the keySet() returned will has one entry inside , and its size is 1.
这篇关于在Java中打印HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!