简体   繁体   中英

Implement entrySet for a Map without keys

I have written a TrieMap<V> implements Map<String,V> class which is obviously keyed from Strings. This works fine.

I want to enhance it to be keyed with the more general CharSequence . I believe I have managed to achieve the transform apart from one final issue, I can't create objects of type K .

The signature must now therefore become TrieMap<K extends CharSequence,V> implements Map<K,V> . The problem is, as I am sure you know, a TrieMap does not actually store the original keys. (In fact that is one of its main values, it can therefore often take up much less space than an ordinary map.)

To implement Set<Entry<K, V>> entrySet() I therefore must somehow manufacture objects of type K . Is there any way that can be achieved?

I would define the following interface:

public interface KeyBuilder<K extends CharSequence> {
    public K build(CharSequence value);
}

and provide an implementation of the interface to the TrieMap constructor. When you need to build a new K instance, you ask the interface to do it.

You might use something more apt to your data structure as the parameter to the build method, CharSequence is only a possibility. IF you want to do something more complex, you could structure it like this:

public interface KeyFactory<K extends CharSequence> {
    public KeyBuilder<K> newBuilder();
}

public interface KeySequence<K extends CharSequence> {
    public KeySequence<K> append(char value);
    public K build();
}

With String implementations:

public class StringKeyFactory<String> {
    public KeyBuilder<String> newBuilder() {
        return new KeyBuilder<String>() {
            private final StringBuilder s = new StringBuilder();
            public KeySequence<String> append(char value) {
                s.append(value);
                return this;
            }
            public String build() {
                return s.toString();
            }
        };
    }
}

No, I don't see how it would be possible without taking a Factory<K> as argument in your constructor. This Factory<K> would have the responsibility of creating instances of K based on the elements you have in the TrieMap .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM