java如何给对象填充照片_如何用另一个数组中的对象填充数组(Java)

在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个对象应该更快并且占用更少的内存.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值