Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8268666

Double entries in Hashmap

XMLWordPrintable

      ADDITIONAL SYSTEM INFORMATION :
      All OS/JRE

      A DESCRIPTION OF THE PROBLEM :
      A test might describe the problem the best:

      @Test
      public void hashMapTest()
      {
         Map<UUID, UUID> map = new HashMap<>();
         for (int i = 0; i < 10; i++)
         {
            UUID uuid = UUID.randomUUID();
            map.computeIfAbsent(uuid, key ->
            {
               map.put(uuid,uuid);
               return uuid;
            });
         }
         assertThat(map.size(), is(10));
      }


      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      @Test
      public void hashMapTest()
      {
         Map<UUID, UUID> map = new HashMap<>();
         for (int i = 0; i < 10; i++)
         {
            UUID uuid = UUID.randomUUID();
            map.computeIfAbsent(uuid, key ->
            {
               map.put(uuid,uuid);
               return uuid;
            });
         }
         assertThat(map.size(), is(10));
      }


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      green test
      ACTUAL -
      red test, double enntries

      ---------- BEGIN SOURCE ----------
      @Test
      public void hashMapTest()
      {
         Map<UUID, UUID> map = new HashMap<>();
         for (int i = 0; i < 10; i++)
         {
            UUID uuid = UUID.randomUUID();
            map.computeIfAbsent(uuid, key ->
            {
               map.put(uuid,uuid);
               return uuid;
            });
         }
         assertThat(map.size(), is(10));
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      fix the code and do not add the value inside the computeIfAbsent method

            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: