所以我试图只从一个数组和数组方法创建一个数组集。我有以下代码应该找到所选项目的索引(我已包含注释,以便您了解每种方法应该做什么)。如您所见,在添加项目之前, 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;
}
}