olidev olidev - 1 year ago 54
Java Question

List of entries, how to add a new Entry?

In Java, I am implementing this:

List<Entry<String, Integer>> listObjects = new ArrayList<Entry<String, Integer>>();

but how can I add a new Entry?

as it does not work with:
listObjects.add(new Entry<"abc", 1>());

thanks in advance.

Answer Source

Do you mean Map.Entry? That is an interface (so you can't instantiate without an implementation class, you can learn about interfaces in the Java Tutorial). Entry instances are usually only created by Map implementations and only exposed through Map.entrySet()

Of course, since it's an interface you could add your own implementation, something like this:

public class MyEntry<K, V> implements Entry<K, V> {
    private final K key;
    private V value;
    public MyEntry(final K key) {
        this.key = key;
    public MyEntry(final K key, final V value) {
        this.key = key;
        this.value = value;
    public K getKey() {
        return key;
    public V getValue() {
        return value;
    public V setValue(final V value) {
        final V oldValue = this.value;
        this.value = value;
        return oldValue;

That way you could do listObjects.add(new MyEntry<String,Integer>("abc", 1))

But that doesn't really make sense outside of a map context.