for(int i=0; i< n; i++) {
hashMap.put("Name",name.get(i));
hashMap.put("Website",website.get(i));
}
我想迭代地向HashMap添加多个值 我希望我的输出像这样
如何添加到hashmap,我没有得到预期的结果。
答案 0 :(得分:5)
我猜你想要这个:
for(int i=0; i< n; i++) {
hashMap.put(name.get(i), website.get(i));
}
答案 1 :(得分:2)
值应该用作Map的键。
map.put("Anna","www.anna.com");
答案 2 :(得分:1)
我想你想要:
for(int i=0; i< n; i++) {
hashMap.put("Name:"+name.get(i),"Website:"+website.get(i));
}
答案 3 :(得分:1)
您有一系列(名称,网站)对要存储。我建议您创建一个包含name
和website
字段的课程。它的toString应该产生你想要的字符串。然后,您可以使用任何Set实现(包括HashSet)来存储对。
答案 4 :(得分:0)
为您的数据创建一个类,并根据逻辑键将这些类的对象添加到hashmap中。
以下是示例代码,假设您创建了一个名为Record的类,其中包含属性名称和网站:
class Record {
String name;
String website;
public Record(String name, String website) {
super();
this.name = name;
this.website = website;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
根据密钥添加对象的代码,修改代码以根据所需的密钥添加记录:
Map<String,Record> recordsMap = new HashMap<String, Record>();
for(int i=0; i< n; i++) {
Record record = new Record(name.get(i), website.get(i));
recordsMap.put(name.get(i), record);
}