so i am trying to create an arraySet from only an array and array methods. I have the following piece of code that should find the index of the item chosen (i’ve included comments so you can understand what each method is supposed to do). As you can see the add method calls on the findIndex method before it can add the item. The problem i am having is that the findIndex method brings up an error (missing return value). How would i return just the int index of the item that the code finds? (the question marks in the code are just to show where i am stuck)
/** 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;
}
}
If I’m understanding your question right it should just be this, the ‘return i’ accomplishes what you are asking, the return -1 is for the not found case: