我有一个用方法完成的类:

public int get(int i) throws ArrayIndexOutOfBoundsException {
    if(i < numElements)
        return elements[i];
    else
        throw new ArrayIndexOutOfBoundsException("");
}


现在,我必须确保此方法有效。
我进行了一个测试,以测试长度为0的数组上的get方法。
所以我主要写道:

    try {
      IntSortedArray r3 = new IntSortedArray(0); //I create an array of length 0
      if( **???** ) {
            System.out.println("OK");
        }
        else {
            System.out.println("FAIL");
        }
    } catch(Exception ecc) {
        System.out.println(ecc + " FAIL");
    }


我要如何处理if?谢谢



类IntSortedArray:

private int[] elements;
private int numElements;

public IntSortedArray(int initialCapacity) {
    elements = new int[initialCapacity];
    numElements = 0;
    System.out.println("Lunghezza dell'array: " + elements.length);
}

最佳答案

你可以做

try {
    IntSortedArray r3 = new IntSortedArray(0);
    r3.get(0);
    fail();
} catch(ArrayIndexOutOfBoundsException expected) {
}

07-24 15:27