get方法(Java)的通用数组列表问题

时间:2017-02-20 01:30:34

标签: java arrays list generics methods

所以即时创建一个通用数组列表,我遇到了get方法的问题。我有它验证索引参数,但如果输入的参数超出范围,我也希望它不使用get方法。因此,如果有人要求它在索引20处得到一个值,当只有10个索引时,它会显示一条错误消息并运行下一个代码。 现在它将显示我的错误消息,仍然尝试使用get方法。

public class GenericList<X> {

    // Use an array to create the list
    private X arr[];
    private int size;

    //Constructor for objects of class GSL

    public GenericList(){
        this.newArray();
    }

    // Create a new array

    private void newArray(){
        arr = (X[]) new Object[10];
        size = 0;
    }

    // Expand array

    private void expandArray(){
        X[] arr2;
        arr2 = (X[]) new Object[(int)(arr.length * 1.2)];
        //Copy elements from arr to arr2
        for (int i = 0; i < arr.length; i++)
            arr2[i] = arr[i];
        //Have arr point to new array
        arr = arr2;
    }

    //Return the size of the list

    public int size(){
        return size;
    }


    // Add a value to the list

    public void add(X value){
        if (size == arr.length){
            this.expandArray();
        }
        arr[size] = value;
        size++;
    }

    // Get the value at the specified location in the list

    public X get(int index){
        if (index < 0 || index >= size)
            System.out.println("Index out of bounds");
        return arr[index];
    }

基本上,如果我运行此测试代码:

GenericList<Integer> arr = new GenericList();
list.add(27);
list.get(100);

list.get(0);

它将创建数组,向第一个索引添加27,然后它将停止并在list.get(100)处给出错误。 我试图让它在该测试中抛出错误然后跳过它并运行list.get(0)。

1 个答案:

答案 0 :(得分:2)

您希望使用throw语句抛出错误,而不是打印出错误。您可能需要ArrayIndexOutOfBoundsException或类似的东西。为此,您应该在get方法的开头进行检查:

public X get(int index) throws ArrayIndexOutOfBoundsException{

    if (index < 0 || index >= size)
        throw new ArrayIndexOutOfBoundsException();

    return arr[index];
}

然后问题不在于您的实现,而在于您的测试代码。如果list.get(100);抛出错误,您希望测试代码不会停止:

GenericList<Integer> arr = new GenericList();
list.add(27);

try {

    list.get(100);

}
catch (Exception e) {

    System.out.println(e);

}

list.get(0);