0

所以我试图只从一个数组和数组方法创建一个数组集。我有以下代码应该找到所选项目的索引(我已包含注释,以便您了解每种方法应该做什么)。如您所见,在添加项目之前, findIndex 方法上的 add 方法调用。我遇到的问题是 findIndex 方法引发了错误(缺少返回值)。我将如何只返回代码找到的项目的 int 索引?(代码中的问号只是为了显示我卡在哪里)

/** Find the index of an element in the dataarray, or -1 if not present
 *  Assumes that the item is not null 
 */
private int findIndex(Object item) {

    for(int i=0; i<data.length;i++){
        if(data[i] == item){
            return i;
        }

    }
  return ???
}


/** Add the specified element to this set (if it is not a duplicate of an element
 *  already in the set).
 *  Will not add the null value (throws an IllegalArgumentException in this case)
 *  Return true if the collection changes, and false if it did not change.
 */
public boolean add(E item) {


    if(item == null){
        throw new IllegalArgumentException();
    }
    else if(contains(item) == true){
        throw new IndexOutOfBoundsException();
    }
    else{

        int index = findIndex(item);
        if(index<0||index>count){
            throw new IndexOutOfBoundsException(); 
       }
        ensureCapacity();
        for(int i=count; i>index; i--){
            data[i]=data[i-1];
        }
        data[index] = item;
        count++;
        return true;
    }
}
4

4 回答 4

0

在大多数情况下,您已经在评论中回答了您自己的问题。找不到项目时应该返回哪个整数?它不能是集合中某些东西的有效值(想想 0 <= x < list.size())。

于 2012-08-13T14:44:58.093 回答
0

如果我正确理解您的问题,则应该是这样,“return i”完成了您的要求,return -1 用于未找到的情况:

private int findIndex(Object item) {

  for(int i=0; i<data.length;i++){
    if(data[i] == item){
        return i;
    }
  }
  return -1;
}
于 2012-08-13T14:46:11.413 回答
0

声明为返回值的方法必须返回值或抛出异常,无论如何。在您迄今为止编写的代码中,只有当您真正找到所需内容时才返回一个值。当你没有找到你要找的东西时,该方法应该怎么做?它也需要返回一些东西。

通常做的是返回一个不可能是索引的特殊值。提示:Java 中从不使用什么样的整数作为数组索引?返回其中之一。然后记录这个选择,调用你的方法的代码必须检查这个特殊的返回值,看看是否找到了该项目。

于 2012-08-13T14:47:13.583 回答
0

您应该return i像现在一样在循环的中间。

但是您还需要一个 return 语句,以防永远无法到达 if 语句。由于您的评论说您应该使用-1,因此您需要return -1一个return ???

于 2012-08-13T14:48:15.447 回答