在java中无法在运行时更改数组大小

时间:2011-10-13 21:14:07

标签: java arrays

我是java的新手,我正试图将我的经验从c#world移植到java这里是代码:

public class TestBasket {

    private Item[] shops  = {} ; 
    int arraysIndex=0;

    public static void main(String argc[]){


        TestBasket tb = new TestBasket();

        try{
        tb.storeItems(new Item("test", 100));
        }
        catch(Exception e){
            System.out.println("Error");
            System.out.println(e.toString());
        }
        }

    public void storeItems(Item it){

        if (arraysIndex >= shops.length){

            ///resizeArray(shops);
            System.out.println("the count of length is" + shops.length);
            cpArr(shops);
            System.out.println("the count of length is" + shops.length);

        }
        shops[arraysIndex] = it;
        arraysIndex++;


    }



    //this is a generic method to resize every kind of array 

    public Item[] cpArr(Item[] arr){
        Item[] retArr = Arrays.copyOf(arr, arr.length + 10);
        return retArr;
    }
}

执行程序后,我会收到此消息:

  

长度为0

     

长度为0

     

错误

     

java.lang.ArrayIndexOutOfBoundsException:0

这意味着数组的长度仍然是零,它不应该为零。 我很困惑我哪里出错了?

问候。


我得到了我的答案,这是我的错,我必须得到回溯值,因为我没有这样做。

3 个答案:

答案 0 :(得分:5)

您没有使用以下结果:

cpArr(shops);

这种方法的作用是创建一个新数组,当前的数组没有任何变化! 所以你需要这样做:

shops = cpArr(shops);

希望这有帮助。

答案 1 :(得分:1)

如果我记得java中的数组有一个固定的大小,你必须在一个新的更大的数组中复制数据。要获得动态尺寸列表,我建议使用Array List

示例:

import java.util.*; //Really generic import
// You can use templates or the generic ArrayList which stores "Object" type
ArrayList<String> myArray = new ArrayList<String>();
// Add one item at a time
myArray.add("Hello");
// Add items from a Collection object
myArray.addAll(Arrays.toList(new String[]{"World", "Just", "Demo"});
// Get item
myArray.get(0);
// Remove item
myArray.remove(0);

我认为你可以猜到其余的(并阅读javadoc)。 希望我可以提供帮助

NB :我暂时没有完成Java,但它应该是正确的。

答案 2 :(得分:0)

您可能想要设置:shop = cpArr(shops)而不是仅调用方法。

相关问题