假设我有两个Collections
:
Collection< Integer > foo = new ArrayList< Integer >();
Collection< Integer > bar = new ArrayList< Integer >();
有时我希望单独迭代它们,但有时也想一起迭代。是否有一种方法可以创建一个 foo
和 bar
的包装器,以便我可以迭代组合的对,但同时也在 foo
和 bar
更改时进行更新?(即Collection.addAll()
不适用)。
例如:
Collection< Integer > wrapper = ... // holds references to both bar and foo
foo.add( 1 );
bar.add( 99 );
for( Integer fooInt : foo ) {
System.out.println( fooInt );
} // output: 1
for( Integer barInt : bar ) {
System.out.println( barInt );
} // output: 99
for( Integer wrapInt : wrapper ) {
System.out.println( wrapInt );
} // output: 1, 99
foo.add( 543 );
for( Integer wrapInt : wrapper ) {
System.out.println( wrapInt );
} // output: 1, 99, 543
谢谢!