Betty Jones
Betty Jones

Reputation: 73

Passing an array of object from one class to another

I've been trying to create a program where it takes an array input through an object and passes the parameter (simulation of ArrayList).

I keep getting the java.lang.ArrayIndexOutOfBoundsException in which I'm guessing I'm not accessing the array properly..

What can I do to enhance the test object and/ or the constructor?

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( )........

Below is the class I am having trouble with.

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);
}
}

Upvotes: 0

Views: 2217

Answers (1)

Perception
Perception

Reputation: 80598

This line from your constructor is the only location (in the code you've shown) where the array x is initialized:

x = new int[0];

And it creates a zero length array. Assuming you are not reinitializing the array somewhere else then all these lines will definitely fail:

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

Because your array length is zero. So:

  1. Initialize your array to a more sensible value
  2. Consider encapsulating the array so that callers cannot directly access it. This will make it much easier to code up your application in the long run

Side note (aka bonus):

This other constructor of yours:

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

has some issues as well:

  1. You should reinitialize your array x to be the same size as the supplied array, prior to copying over the values.
  2. The assignment k = x is basically a no-op, because it doesn't actually change what k was pointing to outside of the method.

Overall, it should look more like this:

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;
    }
}

Upvotes: 1

Related Questions