将一个对象数组从一个类传递到另一个类

时间:2013-04-19 01:54:48

标签: object constructor arraylist parameter-passing

我一直在尝试创建一个程序,通过对象获取数组输入并传递参数(模拟ArrayList)。

我一直得到 java.lang.ArrayIndexOutOfBoundsException ,其中我猜我没有正确访问数组..

如何增强测试对象和/或构造函数?

public class MyArrayList{

 public int[] x; 


 public MyArrayList(  ){
    x = new int[0];
 }

 public MyArrayList(int[] k)
 {
    for (int i = 0; i < x.length; i++)
    x[i] = k[i];
    k = x; 
 }

 public void add(int index).......
 public int size().....
 public int get(int index).....
 public void set(int index, int value).......
 public String toString( )........

以下是我遇到麻烦的课程。

public class TestMyArrayList
 {
  public static void main(String[] args)
  {
     MyArrayList test = new MyArrayList();

     test.x[0] = 1;
     test.x[1] = 2;
     test.x[2] = 3;
     test.x[3] = 4;
     test.x[4] = 5;

     test.add(2);
     test.set(1,3);

     int a, b;
     String c;

     a = test.size( );
     b = test.get(5);
     c = test.toString( );

     System.out.println("The size of the array is" + a);
     System.out.println("The value at that position is " + b);
     System.out.println("The resulting string is: " + c);
}
}

1 个答案:

答案 0 :(得分:1)

构造函数中的这一行是数组x初始化的唯一位置(在您显示的代码中):

x = new int[0];

它创建一个零长度数组。假设您没有在其他地方重新初始化阵列,那么所有这些线肯定会失败:

 test.x[0] = 1;
 test.x[1] = 2;
 test.x[2] = 3;
 test.x[3] = 4;
 test.x[4] = 5;

因为您的数组长度为零。所以:

  1. 将数组初始化为更合理的值
  2. 考虑封装数组,以便调用者无法直接访问它。从长远来看,这将使您更容易编写应用程序
  3. 旁注(又名奖金):

    你的其他构造函数:

    public MyArrayList(int[] k) {
        for (int i = 0; i < x.length; i++)
        x[i] = k[i];
        k = x; 
    }
    

    也有一些问题:

    1. 在复制值之前,您应该将数组x重新初始化为与提供的数组相同的大小。
    2. 作业k = x基本上是无操作,因为它实际上并没有改变k指向方法之外的内容。
    3. 总的来说,它看起来应该更像这样:

      public MyArrayList(int[] k) {
          super();
          if(k != null) {
              x = new int[k.length];
      
              for (int i = 0; i < x.length; i++) {
                  x[i] = k[i];
              }
          } else {
              x = null;
          }
      }
      
相关问题