对于最复杂但最节省内存的解决方案,您可以将它们封装在一个对象中。该对象提供了一个跨所有项目的Iterator<T>
和一个copyTo
方法来复制到新数组。它可以很容易地增强以提供getter和setter。
public class JoinedArray<T> implements Iterable<T> {
final List<T[]> joined;
public JoinedArray(T[]... arrays) {
joined = Arrays.asList(arrays);
}
public Iterator<T> iterator() {
return new JoinedIterator<T>(joined);
}
private class JoinedIterator<T> implements Iterator<T> {
Iterator<T[]> i;
T[] a;
int ai;
T next = null;
private JoinedIterator(List<T[]> joined) {
i = joined.iterator();
a = nextArray();
}
private T[] nextArray () {
ai = 0;
return i.hasNext() ? i.next() : null;
}
public boolean hasNext() {
if (next == null) {
if (a != null) {
if (ai >= a.length) {
a = nextArray();
}
if (a != null) {
next = a[ai++];
}
}
}
return next != null;
}
public T next() {
T n = null;
if (hasNext()) {
n = next;
next = null;
} else {
throw new NoSuchElementException();
}
return n;
}
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
public int copyTo(T[] to, int offset, int length) {
int copied = 0;
for (T[] a : joined) {
if (length <= 0) {
break;
}
if (offset < a.length) {
int n = Math.min(a.length - offset, length);
System.arraycopy(a, offset, to, copied, n);
offset = 0;
copied += n;
length -= n;
} else {
offset -= a.length;
}
}
return copied;
}
public int copyTo(T[] to, int offset) {
return copyTo(to, offset, to.length);
}
public int copyTo(T[] to) {
return copyTo(to, 0);
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
Separator comma = new Separator(",");
for (T[] a : joined) {
s.append(comma.sep()).append(Arrays.toString(a));
}
return s.toString();
}
public static void main(String[] args) {
JoinedArray<String> a = new JoinedArray<String>(
new String[]{
"One"
},
new String[]{
"Two",
"Three",
"Four",
"Five"
},
new String[]{
"Six",
"Seven",
"Eight",
"Nine"
});
for (String s : a) {
System.out.println(s);
}
String[] four = new String[4];
int copied = a.copyTo(four, 3, 4);
System.out.println("Copied " + copied + " = " + Arrays.toString(four));
}
}