【发布时间】:2016-04-06 11:33:04
【问题描述】:
我有一个 for 循环,我在 for 循环中向 HashMap 添加值。基本上我有一个帖子,它有 cmets。一篇文章有 8 个 cmets,我需要我的 HashMap 内容如下所示:
PostId1, comment1
PostId1, comment2
PostId1, comment3
PostId1, comment4
PostId1, comment5
PostId1, comment6
PostId1, comment7
PostId1, comment8
但是,现在我的 hashmap 只包含第一个值。仅在第一次迭代中将值添加到 HashMap,如何在所有 8 次迭代中将值添加到 hashmap。
PS:所有八个值的 PostID 应该相同。
我当前的代码:
for (int i2 = 0; i2 < conversationArray.length(); i2++) {
JSONObject conversationArray1 = conversationArray.getJSONObject(i2);
contentConversation = conversationArray1.getString("content");
commenterId = conversationArray1.getString("commenterId");
commenterName = conversationArray1.getString("commenterName");
commenterPhotos = conversationArray1.getString("commenterPhotos");
postIdForComments = conversationArray1.getString("postId");
lastDateUpdatedConversation = conversationArray1.getString("lastDateUpdated");
dateCreatedConversation = conversationArray1.getString("dateCreated");
commentDescription.add(contentConversation);
commentUserName.add(commenterName);
commentProfileImageLink.add(commenterPhotos);
commentProfileImageHashMap.put(postIdForComments, commenterPhotos);
commentDescriptionHashMap.put(postIdForComments, contentConversation);
commentUserNameHashMap.put(postIdForComments, commenterName);
}
请让我知道我应该对代码进行哪些更改以实现我的目标。欢迎所有建议。
【问题讨论】:
-
您似乎不清楚 HashMap 的工作原理——条目对的第一项,即键,必须是唯一的,否则您不应该使用 HashMap .您可能想要使用的是作为
HashMap<String, ArrayList<String>>实现的Map<String, List<String>>。 -
@HovercraftFullOfEels 好的。我会努力实现的。