[英]A collection that represents a concatenation of two collections in Java
是否有一個類表示集合與另一個集合的串聯? 這個類本身應該是一個Collection,並且應該將所有方法委托給底層(內部)集合 - 不應該分配額外的內存,也不應該修改任何原始集合。
用法示例:
Collection<String> foo = ...
Collection<String> bar = ...
// this should be O(1) memory and time
Collection<String> combined = concat(foo, bar);
if (combined.contains("Zee"))
...
for (String str : combined)
System.out.println(str);
與任何收藏品一樣,請查看google-collections 。 如果您有Set
,特別是(不僅僅是一般集合),您需要:
Set<String> combined = Sets.union(foo, bar);
這會創建兩組的不可修改的視圖。 也就是說, foo
或bar
變化將反映在combined
(但不支持combined.add()
等)。
對於更通用的情況,你有Iterables.concat()
但只是讓你迭代連接的項目, Iterable
接口顯然不包含contains
所以你有點在那里。
google-collections中的其他集合實用程序類( com.google.common.collect.Lists
和com.google.common.collect.Collections2
)不包含任何串聯方法。 不明白為什么他們不能,但目前他們不這樣做。
你的問題非常模糊。 特別是“與另一個項目另一個集合”是非常不清楚的。
您至少可以使用Collection#addAll()
將另一個Collection
的內容添加到當前Collection
。 這里Collection
可以是其子接口/實現的任何內容,例如List
或Set
。
例:
List<String> foos = Arrays.asList("foo1", "foo2", "foo3");
List<String> bars = Arrays.asList("bar1", "bar2", "bar3");
foos.addAll(bars); // Now foos contains everything.
編輯 :還是你真的想創建一個新的 Collection
基於現有的Collection
,然后添加一個新的項目呢? 在這種情況下,只需使用現有的Collection
作為構造函數參數構造一個新的Collection
。 例如:
List<String> foos = Arrays.asList("foo1", "foo2", "foo3");
List<String> bars = new ArrayList<String>(foos);
bars.add("bar"); // Now bars contains everything.
沒有,但自己寫作應該是直截了當的
package ch.akuhn.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Concat {
public static <T> Iterable<T> all(final Iterable<T>... iterables) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
Iterator<Iterable<T>> more = Arrays.asList(iterables).iterator();
Iterator<T> current = more.hasNext() ? more.next().iterator() : null;
@Override
public boolean hasNext() {
if (current == null) return false;
if (current.hasNext()) return true;
current = more.hasNext() ? more.next().iterator() : null;
return this.hasNext();
}
@Override
public T next() {
if (!hasNext()) throw new NoSuchElementException();
return current.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
然后
for (Object each: Concat.all(collection,whatever,etcetera,...)) {
// ...
}
剛剛在這里編寫了這段代碼,編譯風險自負!
PS, 如果你要為這堂課編寫單元測試,請發送給我。
我認為你所要求的是一個Java結構,它允許你將集合放在一起而不需要修改原始集合。 換句話說,您有集合A和B,分別為N和M. 在連續調用之后,你仍然有集合A和B,它們的大小仍然是N和M,但是你也有集合C,它指向A和B,使其大小為N + M.
答案是否定的,Java沒有任何開箱即用的功能......但是你可以編寫一個快速包裝器來包裝一系列集合並將這些集合添加到它。 (它只會維護對每個集合的引用)並且您可以根據需要公開get / insert方法。
Apache Commons Collections還有一個更通用的CompositeCollection類,可以用作任意數量Collection
的接口。
我不確定你的要求。 我對你的問題的解釋是你在Collection上尋找add方法。 我不認為這是你問的問題。
嘗試InterleavingEnumeration或apache的commons集合' ListUtils (ListUtils.union())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.