0

I have read some of the questions (one,two) regarding having duplicate keys in the LinkedHashMap. But I have a specific requirement to handle a scenario in legacy code.

I have LinkedHashMap<String,String> in the code, I need to modify the code to support duplicate Keys. I created below class

public class StringContainer {
    private String data;

    public StringContainer(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return this.data;
    }

    @Override
    public int hashCode() {
        return 10;
    }
}

And modified the code to LinkedHashMap<StringContainer,String>. Now my code works fine as I broke the equal() method by not overriding. Is this approach is fine? Any hidden issues I will face (other than performance)?

Jon B
  • 51,025
  • 31
  • 133
  • 161
mahesh
  • 1,311
  • 1
  • 13
  • 26
  • 1
    Wouldn't it be easier to just replace the map with something more appropriate? Like a `List` for example. – biziclop Feb 21 '18 at 16:32
  • Possible duplicate of [What happens if we override only hashCode() in a class and use it in a Set?](https://stackoverflow.com/questions/26302169/what-happens-if-we-override-only-hashcode-in-a-class-and-use-it-in-a-set) – tsolakp Feb 21 '18 at 16:35
  • I assume this is not possible because of legacy code (although this would be the best solution). Are you sure that your code works now? iirc `HashMap` use the `hashCode()` method to determine the keys. So by setting the hash code to a fixed number you probably can not create a hash map with more than one value. Also I don't think that this is a very good solution because other people may rely on `equals` and `hashCode` to be working as they are intended. – Markus Köbele Feb 21 '18 at 16:37
  • @MarkusK Yes code is working fine in prod,You can store multiple values with same key – mahesh Mar 22 '18 at 18:55

0 Answers0