java - 如何通过引用 Java 中包含数组的 HashMap 来向数组添加值?

标签 java arrays hashmap iteration

这是我的数据集:

<zoo>
  <animal type="dog" breed="beagle" name="charlie" />
  <animal type="dog" breed="beagle" name="chester" />
  <animal type="dog" breed="retriever" name="goldie" />
  <animal type="duck" breed="mallard" name="lord quackerton" />
</zoo>

我想将这些数据转换为一个大的 Java 对象,即数组 HashMap 的 HashMap 。为此,我编写了以下代码:

Map<String, Map<String, ArrayList<String>>> expectedTypes = new HashMap();
Map<String, ArrayList<String>> expectedBreeds = new HashMap();
ArrayList<String> expectedNames = new ArrayList();

// Each <animal> element has already been stored in an array called 'zoo'
for( int i = 0; i < zoo.length; i++) {
    // Grab string values from XML file, using XMLbeans:
    String thisExpectedType = tests[i].getType();
    String thisExpectedBreed = tests[i].getBreed();
    String thisExpectedName = tests[i].getName();

    // Store grabbed strings into the proposed object:
    expectedNames.add(thisExpectedName);
    expectedBreeds.put(thisExpectedBreed, expectedNames);
    expectedTypes.put(thisExpectedType, expectedBreeds);
}

几乎正在做我想做的事。 HashMap 设置得很好,但在底层,它们都存储相同的 expectedNames 数组。它看起来像这样:

- dog
  - beagle
    - 0 charlie
    - 1 chester
    - 2 goldie
    - 3 lord quackerton
  - retriever
    - 0 charlie
    - 1 chester
    - 2 goldie
    - 3 lord quackerton
- duck
  - mallard
    - 0 charlie
    - 1 chester
    - 2 goldie
    - 3 lord quackerton

但这就是我需要的:

- dog
  - beagle
    - 0 charlie
    - 1 chester
  - retriever
    - 0 goldie
- duck
  - mallard
    - 0 lord quackerton

我想我需要看看 i 处的 thisExpectedBreed 是否已经存在,如果不存在,则创建一个新数组并将其放入 HashMap 中。但我怎样才能做到这一点呢?如何确保每个 expectedBreeds Map 都有自己唯一的数组并将值正确添加到每个数组?

如果有帮助的话,数据集按类型排序,然后是品种,然后是名称,因此逻辑不必预计任何跳跃。例如,一旦对一个品种进行了编目,我就不必再处理该品种的任何元素。

最佳答案

您需要为每个 map 创建一组名称,而不是重复使用同一组名称

// Each <animal> element has already been stored in an array called 'zoo'
for( int i = 0; i < zoo.length; i++) 
{
    ...

    // get the names for this breed
    ArrayList<String> expectedNames = expectedBreeds.get(thisExpectedBreed);
    // if there aren't any, start a new collection
    if (expectedNames == null)
    {
        expectedNames = new ArrayList<String>();
        expectedBreeds.put(thisExpectedBreed, expectedNames);
    }
    expectedNames.add(thisExpectedName);
    ...

现在您在所有动物中重复使用相同的名称

关于java - 如何通过引用 Java 中包含数组的 HashMap 来向数组添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143326/

相关文章:

java - Java中包和子包的关系

Java求直线的交点并找到它的坐标和它右边或下面最近的邻居

java - 组合游戏中的元素

javascript - 使用多个过滤器数组过滤一个数组

c - 为什么二进制数据文件比数据大?

java - 添加重复元素时不会发生 ConcurrentModificationException

java - 如何使用 Jackson 将 json 数组转换为 java hashmap

java - 尝试运行一个简单的 Java ActionListener 示例并收到错误?

javascript - 如何使用 JavaScript 更新或添加数组中的值?

java - 有没有办法让 if(null) 做某事