jl90
jl90

Reputation: 649

Inserting values into HashMap not functioning properly

I am trying to insert values of a String and ArrayList<String> into a HashMap<String, ArrayList<String>>. The code in the for loop works fine but it does not insert the values that I wanted when inserting ArrayList values into the HashMap.

My code:

  for(int i=0; i<fileNames.length; i++)
  {
    File imageFile = new File(fileNames[i]);
    metadata = ImageMetadataReader.readMetadata(imageFile);

    String[] results;
    container.clear();
    println(container);

    for (Directory directory : metadata.getDirectories())
    {
      for (Tag tag : directory.getTags())
      {
        if(tag.getTagName() == "Keywords")
        {
          results = tag.getDescription().split(";");

          for(int k=0; k<results.length; k++)
          {
            keywords.add(results[k]);
            container.add(results[k]);
          }
          println(fileNames[i] + ", " + container);
          imageTag.put(fileNames[i], container);
        } 
      }
    }
  }

  println(imageTag.entrySet());
}

which prints out:

[]
gardensbythebay.jpg, [gardens, gardens by the bay, supertree, singapore]
[]
mbs.jpg, [marina, bay, sands, ferris, wheel, skyline, singapore]
[]
supertree.jpg, [architecture, marina, gardens, bay, tower, supertree, singapore, gardens by the bay, plants, nature]
[]
uss.JPG, [universal, uss, rws, resort, world, sentosa, studios]

[mbs.jpg=[universal, uss, rws, resort, world, sentosa, studios], 
uss.JPG=[universal, uss, rws, resort, world, sentosa, studios], 
supertree.jpg=[universal, uss, rws, resort, world, sentosa, studios], 
gardensbythebay.jpg=[universal, uss, rws, resort, world, sentosa, studios]]

Upvotes: 0

Views: 373

Answers (3)

JB Nizet
JB Nizet

Reputation: 692181

At each iteration, you're clearing your container, add elements to it, and then add the container to the map.

The map only stores references. It doesn't make a copy of the list. So you end up with all the keys having the same value: the container list, containing what the last iteration added to it.

Each iteration should create a new list, and add this list to the map.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425358

This is a bug:

if (tag.getTagName() == "Keywords")

This will never be true. You should use:

if (tag.getTagName().equals("Keywords"))

But your main problem is you are reusing the same container for each entry. You should create a new one each entry, otherwise you are clearing and adding to the same map value over and over.

Upvotes: 0

assylias
assylias

Reputation: 328873

You keep reusing the same ArrayList. So when you clear it, it also clears what you previously placed in the map. And when you populate it it populates what is already in the map too. So you end up with all your keys pointing to the same list which contains the data of your last run.

You need to create a new ArrayList for each entry.

Upvotes: 3

Related Questions