01: /* DualCollection.java
02:
03: {{IS_NOTE
04: Purpose:
05:
06: Description:
07:
08: History:
09: Sun Sep 2 21:29:38 2007, Created by tomyeh
10: }}IS_NOTE
11:
12: Copyright (C) 2007 Potix Corporation. All Rights Reserved.
13:
14: {{IS_RIGHT
15: This program is distributed under GPL Version 2.0 in the hope that
16: it will be useful, but WITHOUT ANY WARRANTY.
17: }}IS_RIGHT
18: */
19: package org.zkoss.util;
20:
21: import java.util.Collection;
22: import java.util.Collections;
23: import java.util.Iterator;
24: import java.util.AbstractCollection;
25:
26: /**
27: * A combination of two collections into a collection.
28: *
29: * @author tomyeh
30: * @since 3.0.0
31: */
32: public class DualCollection extends AbstractCollection implements
33: java.io.Serializable {
34: private final Collection _first, _second;
35:
36: /** Returns a collection by combining two collections.
37: * It checks whether any of them is null, or equals. And, returns
38: * the non-null one if another is null.
39: * If both null, it returns null.
40: */
41: public static final Collection combine(Collection first,
42: Collection second) {
43: if (first == second) //we don't use equals to have better performance
44: return first;
45:
46: if (first != null)
47: if (second != null)
48: return new DualCollection(first, second);
49: else
50: return first;
51: else
52: return second;
53: }
54:
55: /** Constructor.
56: * It is better to use {@link #combine} instead of this method
57: * since it checks whether any of them is null or equals.
58: */
59: public DualCollection(Collection first, Collection second) {
60: _first = first != null ? first : Collections.EMPTY_LIST;
61: _second = second != null ? second : Collections.EMPTY_LIST;
62: }
63:
64: //Collection//
65: public int size() {
66: return _first.size() + _second.size();
67: }
68:
69: public Iterator iterator() {
70: return new Iter();
71: }
72:
73: private class Iter implements Iterator {
74: private Iterator _it;
75: private boolean _bSecond;
76:
77: private Iter() {
78: _it = _first.iterator();
79: }
80:
81: public boolean hasNext() {
82: return _it.hasNext() || (!_bSecond && !_second.isEmpty());
83: }
84:
85: public Object next() {
86: if (!_bSecond && !_it.hasNext()) {
87: _it = _second.iterator();
88: _bSecond = true;
89: }
90: return _it.next();
91: }
92:
93: public void remove() {
94: _it.remove();
95: }
96: }
97: }
|