私自身のArrayListクラスを作成しようとしています。なぜArrayStoreExceptionがスローされるのですか?
私のコードは次のようである:
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));
}
}
私はINCREASESIZE内のオブジェクトをinitilizeしようとしている場合、私は()でArrayStoreExceptionを取得します。私が最初にオブジェクトを初期化している場合、私はもう例外を取得しません。
誰でも私にこの理由を説明できますか?
ヒント:例外を作成して投げるときには、**メッセージ**を提供することを検討してください。デバッグをはるかに簡単にします。今すぐあなたは今いくつかの例外がスローされたことになります。デバッグに役立つ情報(currentSizeやindexの値など)は提供していません。そして、あなたのブロックの周りに{}を常に使用してください。たとえそれがちょうど1行のものであったとしても。 – GhostCat
'objects = new Objects [1]' - オブジェクトです** ** typoですか? – Eran