List of records, how to add a new record?

In Java, I implement this:

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

but how to add a new record?

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

early.

+3
source share
5 answers

Do you mean Map.Entry? This is an interface (therefore, you cannot create an instance without an implementation class; you can learn about interfaces in the Java tutorial ). Entryinstances are usually created only Mapand displayed only throughMap.entrySet()

Of course, since this is an interface, you can 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;
    }
}

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

But this really does not make sense outside the context of the map.

+4
source

, , :

listObjects.add(new java.util.AbstractMap.SimpleEntry<String, Integer>("abc", 1));

- , !

, : -)

+8

Entry - , Entry ( ).

Entry: ( , , ):

// create a list
List<Entry<String, Integer>> listObjects = 
               new ArrayList<Entry<String, Integer>>()

// create an instance of Entry
Entry<String, Integer> entry = new Entry<String, Integer>("abc", 1);

// add the instance of Entry to the list
listObjects.add(entry);

Map.Entry (OP , Entry Map.Entry . Map.Entry, :

Map<String, Integer> map = getMapFromSomewhere();
List<Map.Entry<String, Integer>> listObjects = 
               new ArrayList<Map.Entry<String, Integer>>();

for (Map.Entry<String, Integer> entry:map.entrySet())
    listObjects.add(entry);
+4

Entry - Guava - listObjects.add(Maps.immutableEntry("abc",1));

+2

Maybe listObjects.add(new Entry<String, Integer>("abc", 1));? Generics determine type ( String, Integer), not values ​​( abc, 1).

Change Note that it was later added, which Entryis actually Map.Entrywhy you need to create an implementation Map.Entrythat you later create, exactly as the selected answer explains.

0
source

All Articles