作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试使用 52 个对象的数组(带有花色和值的卡片)并创建一个包含相同 52 个对象但多次的数组。 (就好像我在一副大牌中有多副 52 张牌)。
我的默认构造函数填充一副牌的数组如下所示:
public Deck() {
allocateMasterPack(); //creates and fills the "model" deck
cards = new Card[masterPack.length];
for (int i = 0; i < masterPack.length; i++) {
cards[i] = new Card(masterPack[i]);
}
我如何才能填充两副牌(104 张卡片对象,52 张牌重复两次)、三副或四副牌的数组?
最佳答案
在 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<Card[]> into a Stream<Card> 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
元素复制到 cards
数组中的位置 0 到 51,第二次迭代复制到位置 52 到 103。
您的 Card
对象应该是不可变的,因此无需每次都创建新的 Card
副本。引用相同的 52 个对象应该更快并且占用更少的内存。
关于java - 如何用另一个数组中的对象填充一个数组 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762232/
我是一名优秀的程序员,十分优秀!