如何用另一个数组中的对象填充数组(Java)

时间:2015-04-21 03:12:31

标签: java arrays

我尝试使用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个卡片组重复两次),或三个或四个?

3 个答案:

答案 0 :(得分:5)

在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)
  

参数:
  src - 源数组。
  srcPos - 源数组中的起始位置   dest - 目标数组。
  destPos - 目标数据中的起始位置。
  length - 要复制的数组元素的数量。

例如,如果您想将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,第二次迭代复制到cards数组中的位置52到103。

您的Card对象应该是不可变的,因此不需要每次都创建新的Card个副本。引用相同的52个对象应该更快并且占用更少的内存。

答案 1 :(得分:3)

int repetitions;

for(int i = 0 ; i < masterPack.length * repetitions ; i++)
     cards[i] = new card(masterPack[i % masterPack.length]);

答案 2 :(得分:1)

尝试使用ArrayList进行纸牌游戏。

public Deck() {
int repetitions;     
ArrayList<Card> cards = new ArrayList<Card>();

for (int x = 0; x < repititions; x++)
    for (int i = 0; i < masterPack.length; i++) 
        cards.add(new Card(masterPack[i]));
相关问题