【问题标题】:Generic Array List issue with get method (Java)get方法的通用数组列表问题(Java)
【发布时间】:2017-07-09 04:12:30
【问题描述】:

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

【问题讨论】:

  • 当您询问有关代码中的错误的问题时,发布完整的错误消息并在您的代码中指出导致错误的行会是明智且有帮助的。
  • 如果索引超出范围,您需要抛出异常。您的代码没有这样做。
  • 线程“main”java.lang.Error 中的异常:未解决的编译问题:此方法必须在 GenericList.get(GenericList.java:52) 处返回 X 类型的结果
  • 当然它仍然会这样做。您当前所做的只是打印一份声明。如果有人打印某些东西后功能停止了,那么会有很多功能不起作用
  • 应该“继续”是什么意思?如果非 void 方法正常完成,必须返回一个值。您决定该值应该是什么并返回它。 (提示:可能是null

标签: java arrays list generics methods


【解决方案1】:

您不想打印出错误,而是使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多