链接列表并引发异常

时间:2020-03-01 18:10:39

标签: java

我的问题是关于实现方法get(int n),该方法应返回索引n处的元素(索引从0开始)。如果索引超出范围,则应引发异常IllegalArgumentException。 这是我写的代码,是正确的还是应该更改某些内容?

(整数大小)以获取数组列表

public Item get(int size) {
        Node<Item> n= head;
        for (int i=0; i<=size;i++)
            n=n.next;

        if ( size < 0 ) { throw new UnsupportedOperationException();}       
        return null;*

2 个答案:

答案 0 :(得分:1)

您可以简化在循环之前从头开始编写的第一个检查:

if (head == null || size < 0) {
    throw new UnsupportedOperationException();
}

在循环中,您必须检查自己是否不在列表中:

if (n == null) {
    throw new UnsupportedOperationException();
}

最后,在循环之后,您必须返回找到的实际元素:

return n.getItem();

还要注意,sizen混淆了变量名,最好将它们命名为indexcurrent。考虑到我的所有建议,代码如下所示:

public Item get(int index) {

    if (head == null || index < 0) {
        throw new UnsupportedOperationException();
    }

    Node current = head;

    for (int i = 0; i < index; i++) {
        if (current == null) {
            throw new UnsupportedOperationException();
        }
        current = current.next();
    }

    return current.getItem();

}

答案 1 :(得分:0)

您的代码应如下所示:

public Item get(int size){
   if(head == null || size < 0){
      throw new UnsupportedOperationException();
   }
   else{
      Node n = head;
      for(int i=0; i <=size;i++){
         if(n == null){
            throw new UnsupportedOperationException();
         }
         if(i != 0){
            n = n.next();
         }
      }
      return n.getItem();
   }
 return null;  
}