Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-7802

MapWithDefault should be able to be configured to not store its default value

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.4.6
    • 4.0.1
    • groovy-jdk
    • None
    • Patch

    Description

      As described in https://github.com/apache/groovy/pull/267, a Groovy map with a default value stores all the accessed elements, even if they weren't added explicitly, just queried.

      In certain algorithms (e.g. https://github.com/careercup/CtCI-6th-Edition-Groovy/blob/d116d65469bdf17d1e215e89f3e76ac3a97660a9/src/main/groovy/Ch04_TreesAndGraphs/_04_12_PathsWithSum.groovy#L21) the complexity would automatically be reduced, if default values would be deleted (i.e. a default of 0 that is incremented and decremented in a recursive algorithm).

      Topics of discussion:

      • Currently a `getAt` will `add` also, therefore `containsKey` isn't the same as `getAt(...) != null`
      • After the change `keySet()/entrySet()` wouldn't include default values

      I proposed alternatives:

      • `removeIfDefault(Object)` // removes current key, if value is equal to default
      • `consolidate()` // removes all default values
      • constructor parameter `STORE_DEFAULT storeDefaultValues = STORE_DEFAULT.FALSE`, or maybe with a `boolean`, though I find primitive parameters confusing

      others:

      • `containsKey` should always return `true`, or throw an exception, since its behavior is inconsistent

      Waiting for your thoughts

      Attachments

        Activity

          People

            paulk Paul King
            papuska@gmail.com Pap LÅ‘rinc
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: