0

I made a class extending ArrayList called sortedWordList that holds and sorts Strings. I would like to implement a binary search to override the indexOf method.

I cannot use compareTo to compare my Strings. I understand that I am passing the type Object to compareTo, but I believe that has to be my parameter type in order to override ArrayList's indexOf method.

My binary search algorithm may be incorrect as I have not had a chance to debug it yet so you may ignore that.

@Override
public int indexOf(Object o) {

    int min = 0;
    int max = len - 1;
    while (true){
        int mid = (int)((min + max)/ 2);
        if (this.get(mid).compareTo(o) == 0){
            return(mid);
        }
        if (this.get(mid).compareTo(o) < 0){
            min = mid;
        }
        else if (this.get(mid).compareTo(o) > 0){
            max = mid;
        }


        if (max == mid) break;

    }

    return -1;
}

1 Answer 1

1

If your this.get(i) returns a String, you might want to make you method signature be

public int indexOf(String o)

and, instead of extending ArrayList, you might want to encapsulate it.

EDIT:

If you're forced to stick with that method signature, covert the Object to String with String.valueOf(o).

Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately, the assignment requires me to override the method :(
Have you tried casting? this.get(mid).compareTo((String) o). It is forcing you to extend ArrayList too? Looks like your assignment is forcing you to write bad code, which is unfortunate for something that is supposed to be teaching the opposite.
It's a bad idea to overload indexOf that way. It would confuse people who already have a hard time with methods that take Object instead of E and this would make it worse. Instead, extract the String.valueOf o (bad variable name) and feed that to compareTo, which does take a generic argument.
If o is null that could complicate matters. It's a good idea to check if o is null and returns "not found" if so, before doing the rest of indexOf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.