John Smith John Smith - 3 months ago 11
Java Question

Why ArrayStoreException is thrown?

I am trying to write my own ArrayList class.

My code is the following:

package test;
import java.util.Arrays;
import java.util.*;

public class MyArrayList
{
private Object[] objects = null;
private int currentSize = 0;


public void add(Object obj)
{
increaseSize();
objects[currentSize++] = obj;

}

public Object get(int index)
{
if (currentSize >= index)
return objects[index];
else
throw new ArrayIndexOutOfBoundsException();
}

public void remove(int index)
{
if(currentSize >= index)
{
for(int i = index; i < currentSize; i++)
{
objects[i] = objects[i + 1];
}
objects[currentSize--] = null;
}
else
throw new ArrayIndexOutOfBoundsException();
}

public int size()
{
return currentSize;
}


private void increaseSize()
{
if (objects == null)
objects = new Objects[1];
else
objects = Arrays.copyOf(objects, objects.length + 1);
}

public static void main(String args[])
{
MyArrayList l = new MyArrayList();
Integer integ = new Integer(1);
l.add(integ);
for(int i = 0; i < l.size(); i ++)
System.out.println("Element " + i + " = " + l.get(i));
}
}


I get ArrayStoreException if I am trying to initilize objects inside increaseSize(). If I am initializing objects at the beginning I don't get that exception anymore.

Can anybody explain me the reason for this ?

Answer

You are creating an array of type Objects:

if (objects == null)
    objects = new Objects[1];

Objects is java.util.Objects, as you have imported everything from java.util:

import java.util.*;

While you probably meant an array of Objects:

if (objects == null)
    objects = new Object[1];

The error occurs when you try to store something in the array - unfortunately array types in Java are covariant, which leads to problems like that.

Comments