-1

What I'm tring to do is to create a HashMap,which looks like this.

enter image description here

I assumed that the wildcard symbol * can be used as a key, so if any character other than a,b and c (let's say x) is searched for, this HashMap will return 10.

 for (int j = 0; j <= 2; j++) {            
        table.put(pattern[j], (pattern.length - 1 - j)); 
        //This part is actually not the same as the original code.
        //The keys are a,b,c, and the values are 1,2,3 respectively     
    }
    table.put('*', 10);

However, when I search this map for a key x, this returns null, so it is clear that * can't be directly used as a wildcard key. I followed this page, but apparently this doesn't work for HashMap.

I'd appreciate if you would give any insight to solve this.

Hiroki
  • 3,893
  • 13
  • 51
  • 90
  • Subclass `HashMap` to make it do what you want, ie. given an value that isn't explicitly mapped, return `10`. – Sotirios Delimanolis Oct 13 '15 at 00:42
  • 3
    The `*` character is not special in HashMaps. HashMaps operate _only_ on the hashCode and equality of their keys -- there is no other magic (other than `null`, I guess, which is special cased to be equal only to itself). There's no more reason for `*` to act like a wildcard than there is for, say, `w` or `☃` to act as wildcards. – yshavit Oct 13 '15 at 00:46
  • 1
    @SotiriosDelimanolis But that would break the contract for `Map`. – Paul Boddington Oct 13 '15 at 00:46
  • @PaulBoddington Nah, just clarify the behavior in the specification for this new class. – Sotirios Delimanolis Oct 13 '15 at 00:47

2 Answers2

3

Java 1.8 support getOrDefault

So u can use map.getOrDefault(key,defaultValue)

Ibraheem
  • 100
  • 9
  • Thank you for your advice, but apparently there isn't a method which can set the default value, is there? – Hiroki Oct 13 '15 at 01:21
  • I'm reading this (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#getOrDefault-java.lang.Object-V-) – Hiroki Oct 13 '15 at 01:21
  • If there is no such a method, I'd override the `getOrdefault(key,defaultValue)` so that I can set the default value. How do you think about this idea? – Hiroki Oct 13 '15 at 01:22
  • You can do that. But the better design , as I think , is to put the default value as a property in the class that uses the map – Ibraheem Oct 13 '15 at 01:25
  • Thank you so much. I feel like I learned a lot from it. – Hiroki Oct 13 '15 at 01:32
0

It's best to just treat it separately, rather than create a new Map class. You could do something like this with some wrapper class:

public Object getWithDefault(key){
    if (hashMap.get(key) == null){
        return hashMap.get("*");
    }
}

Then call it with the wrapper class

wrapper.getWithDefault('d');  // returns 10.
ergonaut
  • 6,929
  • 1
  • 17
  • 47