对于最复杂但最不占用内存的解决方案,您可以将它们包装在一个对象中。这个提供了一个Iterator<T>
跨越所有项目的copyTo
方法和一种复制到新数组的方法。它可以很容易地增强以提供 getter 和 setter。
public class JoinedArray<T> implements Iterable<T> {
final List<T[]> joined;
// Pass all arrays to be joined as constructor parameters.
public JoinedArray(T[]... arrays) {
joined = Arrays.asList(arrays);
}
// Iterate across all entries in all arrays (in sequence).
public Iterator<T> iterator() {
return new JoinedIterator<T>(joined);
}
private class JoinedIterator<T> implements Iterator<T> {
// The iterator across the arrays.
Iterator<T[]> i;
// The array I am working on. Equivalent to i.next without the hassle.
T[] a;
// Where we are in it.
int ai;
// The next T to return.
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) {
// a goes to null at the end of i.
if (a != null) {
// End of a?
if (ai >= a.length) {
// Yes! Next i.
a = nextArray();
}
if (a != null) {
next = a[ai++];
}
}
}
return next != null;
}
public T next() {
T n = null;
if (hasNext()) {
// Give it to them.
n = next;
next = null;
} else {
// Not there!!
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;
// Walk each of my arrays.
for (T[] a : joined) {
// All done if nothing left to copy.
if (length <= 0) {
break;
}
if (offset < a.length) {
// Copy up to the end or to the limit, whichever is the first.
int n = Math.min(a.length - offset, length);
System.arraycopy(a, offset, to, copied, n);
offset = 0;
copied += n;
length -= n;
} else {
// Skip this array completely.
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));
}
}