只是一個例子,你應該怎麼解決的大名單數組複製。當心字符數量必須小於Integer.MAX。這段代碼只是一個例子,它是如何完成的。有很多檢查必須執行它才能使代碼正常工作。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class WrappedList {
//Or replace with some better counter
int totalCharCount = 0;
final List<String> list;
public WrappedList() {
this(new ArrayList<String>());
}
public WrappedList(final List<String> list) {
this.list = list;
}
public void add(final String toAdd) {
if(toAdd != null) {
totalCharCount += toAdd.length();
this.list.add(toAdd);
}
}
public List<String> getList() {
return Collections.unmodifiableList(list);
}
public char[] toCharArray() {
return this.toCharArray(this.totalCharCount);
}
public char[] toCharArray(final int charCountToCopy) {
final char[] product = new char[charCountToCopy];
int buffered = 0;
for (String string : list) {
char[] charArray = string.toCharArray();
System.arraycopy(charArray, 0, product, buffered, charArray.length);
buffered += charArray.length;
}
return product;
}
//Utility method could be used also as stand-alone class
public char[] toCharArray(final List<String> all) {
int size = all.size();
char[][] cpy = new char[size][];
for (int i = 0; i < all.size(); i++) {
cpy[i] = all.get(i).toCharArray();
}
int total = 0;
for (char[] cs : cpy) {
total += cs.length;
}
return this.toCharArray(total);
}
public static void main(String[] args) {
//Add String iteratively
WrappedList wrappedList = new WrappedList();
wrappedList.add("back");
wrappedList.add("pack");
wrappedList.add("back1");
wrappedList.add("pack1");
final char[] charArray = wrappedList.toCharArray();
System.out.println("Your char array:");
for (char c : charArray) {
System.out.println(c);
}
//Utility method one time for all, should by used in stand-alone Utility class
System.out.println("As util method");
System.out.println(wrappedList.toCharArray(wrappedList.getList()));
}
}
參見:system-arraycopy-than-a-for-loop-for-copying-arrays
這不是一般的好主意,依靠的toString的行爲。雖然類似ArrayList的東西不太可能改變toString的實現,但其他類可能會這樣,這意味着您編寫的任何代碼依賴它,它將不再按預期工作。 –