2011-10-13 47 views
0

改变数组的大小,我在Java还挺新的,我想端口从C#世界的java这里我的经验是代码:无法在运行在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; 
    } 
} 

执行程序后,我将得到这个消息:

长度IS0

长度IS0

错误

java.lang.ArrayIndexOutOfBoundsException:0

这意味着仍然阵列的长度是零,这不应该是零。 我很困惑我哪里错了?

关于。


我得到我的回答是我的错,我必须得到retrun值作为结果,我并没有这样做。

+0

既然你已经知道了它,它似乎是微不足道的,请删除问题。 –

+0

或更恰当地说,接受正确的答案。 –

回答

5

您没有使用的结果是:

cpArr(shops); 

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

shops = cpArr(shops); 

希望这会有所帮助。

0

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

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,但它应该是大部分是正确的。