将数组复制到java中的新数组

时间:2015-03-22 02:35:18

标签: java arrays

我的java代码有问题。我想将一个数组复制并复制到一个新数组。它总是在java.lang.ArrayIndexOutOfBoundsException

上给我错误

代码:

public void SetCard(int usrSet)
    {
            //define 52card with number and shape
            String[] cards = {"1a","1d", "1h", "1s", "2a", "2d", "2h", "2s"};
            //set to an global array
            deckCards = null;
            //deckCards = new String[cards.length];
            //deckCards = cards;

            int setLength = cards.length;
            String temp = "";
            if (usrSet >= 1)
            {
                    setLength = setLength * usrSet - 1;
                    int a = 0;
                    deckCards = new String[setLength];
                    System.out.println("Deck Cards now is " + deckCards.length);
                    for (int i = 0; i < usrSet; i++)
                    {
                            for(int j = 0; j < cards.length; j++)
                            {
                                    temp = cards[j];
                                    System.out.println("Position SetL = "+ a + "J is " + j + "Temp = "+ temp);
                                    deckCards[a] = temp;
                                    a++;
                            }
                    }
                    //System.out.println(Arrays.toString(deckCards));
            }


    }

3 个答案:

答案 0 :(得分:0)

你必须删除“ - 1”: setLength = setLength * usrSet - 1; 所以它变成了 setLength = setLength * usrSet;

答案 1 :(得分:0)

如果usrSet大于1,您的代码将给出ArrayIndexOutOfBoundsException。 如果你的目的只是制作一个数组的副本,我不知道你为什么要做这么多事情。可能以下代码就足够了:

String[] deckCards = new String[setLength]; for(int j = 0; j < cards.length; j++){ temp = cards[j]; deckCards[j]= temp; }

如果您可以自由使用其他api,请尝试探索java.util.Arrays

答案 2 :(得分:0)

这里所需要的只是

deckCards = (String[])cards.clone();

clone()数组类型is public