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

Object 将对象数组从一个类传递到另一个类,object,constructor,arraylist,parameter-passing,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)

我一直在尝试创建一个程序,在这个程序中,它通过一个对象接收数组输入并传递参数(模拟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( )........

构造函数中的这一行是数组
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;
因为你的数组长度是零。因此:

  • 将数组初始化为更合理的值
  • 考虑封装数组,以便调用者无法直接访问它。从长远来看,这将使编写应用程序更加容易
  • 旁注(又名奖金): 你的另一个构造器:

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

    第一个构造函数故意初始化一个空数组,这样我就可以使用另一个构造函数来初始化动态数组(从固定的构造函数)。我是否应该编写x=new int[0]来实现这一点(以便以后可以扩展)?好吧,如果要让人们调用第一个构造函数,那么它必须正确初始化数组。要么这样,要么保密。在任何情况下,您都需要能够调整数组的大小以容纳更多的项(我猜您在
    add
    方法中就是这样做的)。
    public MyArrayList(int[] k) {
        for (int i = 0; i < x.length; i++)
        x[i] = k[i];
        k = x; 
    }
    
    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;
        }
    }