在Java 8中,您可以使用
Stream.flatMap()执行此操作:
int n = 2;
Card[] cards = IntStream.range(0, n) // repeat n times
.mapToObj(i -> masterPack) // replace each i with the masterPack
.flatMap(pack -> Arrays.stream(pack)) // turn the Stream into a Stream by flattening it
.toArray(Card[]::new); // create a new array containing all the cards repeated n times
如果您不能使用Java 8,则可以使用System.arraycopy():
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Parameters:
src – the source array.
srcPos – starting position in the source array.
dest – the destination array.
destPos – starting position in the destination data.
length – the number of array elements to be copied.
例如,如果您想将masterPack复制到其大小翻倍的新套牌,您可以执行以下操作:
int n = 2;
Card[] cards = new Card[masterPack.length * n];
for (int i = 0; i < n; i++) {
System.arraycopy(masterPack, 0, cards, i * masterPack.length, masterPack.length);
}
这将循环两次,执行:
System.arraycopy(masterPack, 0, cards, 0, 52);
System.arraycopy(masterPack, 0, cards, 52, 52);
第一次迭代将masterPack元素复制到位置0到51,第二次迭代将复制到卡阵列中的位置52到103.
您的Card对象应该是不可变的,因此无需每次都创建新的Card副本.引用相同的52个对象应该更快并且占用更少的内存.