Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

I'd like to create new item that similarly to Util.Map.Entrythat will contain the structure keyvalue.

The problem is that I can't instantiate a Map.Entry because it's an interface.

Does anyone know how to create a new generic key/value object for Map.Entry?

1 Answer

0 votes
by (46k points)

You can just execute the Map.Entry<K, V> interface yourself:

import java.util.Map;

final class MyEntry<K, V> implements Map.Entry<K, V> {

    private final K key;

    private V value;

    public MyEntry(K key, V value) {

        this.key = key;

        this.value = value;

    }

    @Override

    public K getKey() {

        return key;

    }

    @Override

    public V getValue() {

        return value;

    }

    @Override

    public V setValue(V value) {

        V old = this.value;

        this.value = value;

        return old;

    }

}

And then apply it:

Map.Entry<String, Object> entry = new MyEntry<String, Object>("Hello", 123);

System.out.println(entry.getKey());

System.out.println(entry.getValue());

Related questions

0 votes
1 answer
asked Dec 2, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...