如何修复java代码的以下小片段

时间:2012-08-13 14:41:45

标签: java arrays

所以我试图只从数组和数组方法创建一个arraySet。我有以下代码片段应该找到所选项目的索引(我已经包含了注释,因此您可以了解每个方法应该做什么)。正如您可以在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 个答案:

答案 0 :(得分:0)

大部分时间,您在评论中都回答了自己的问题。无法找到该项目时,应该返回哪个整数?它不能是集合中某些东西的有效值(想想0&lt; = x&lt; list.size())。

答案 1 :(得分:0)

如果我理解你的问题,那就应该是这样,'返回i'完成你所要求的,返回-1是未找到的情况:

private int findIndex(Object item) {

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

你应该像现在一样拥有循环中间的return i

但是如果永远不会达到if语句,你还需要一个return语句。由于您的评论说您应该使用-1,因此您需要return -1 return ???