[英]How to build a new list containing all entries from existing list AND a copy of each entry with one field modified?
[英]List of entries, how to add a new Entry?
在 Java 中,我正在實現這個:
List<Entry<String, Integer>> listObjects = new ArrayList<Entry<String, Integer>>();
但是如何添加新條目?
因為它不適用於: listObjects.add(new Entry<"abc", 1>());
提前致謝。
我知道這是一個相當古老的線程,但您可以按如下方式進行:
listObjects.add(new java.util.AbstractMap.SimpleEntry<String, Integer>("abc", 1));
它可能會幫助像我這樣最近嘗試這樣做的人!
我希望它有幫助:-)
你的意思是Map.Entry
嗎? 那是一個接口(所以你不能在沒有實現 class 的情況下實例化,你可以在 Java 教程中了解接口)。 Entry
實例通常僅由Map
實現創建,並且僅通過Map.entrySet()
公開
當然,由於它是一個接口,您可以添加自己的實現,如下所示:
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;
}
}
這樣你就可以做listObjects.add(new MyEntry<String,Integer>("abc", 1))
但這在 map 上下文之外並沒有真正意義。
Entry
是參數化的class ,您需要使用構造函數創建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);
With Map.Entry
it is somewhat different (OP just mentioned, that Entry
is Map.Entry
in Fact. We can't create Map.Entry
instances, we usually get them from an existing map:
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);
使用現成的Entry
實現的一種方法是Guava 的 Immutable Entry類似這樣的listObjects.add(Maps.immutableEntry("abc",1));
也許listObjects.add(new Entry<String, Integer>("abc", 1));
? generics 指定類型( String
, Integer
),而不是值( abc
, 1
)。
編輯- 請注意,后來添加的Entry
實際上是Map.Entry
,因此您需要創建Map.Entry
的實現,稍后實例化,正如所選答案所解釋的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.