1

I was looking at a previous question submitted a while back and had further inquiry on it. The link is here:

Java BinarySearch

The first answer give it nearly answers my question, but not fully. In the one shown above the Array has a collection of int values. However, I have an array that stores String values, therefore when I call Array[mid] it won't allow this, since mid is an int value and not a String. I receive the error " The operator < is undefined for the argument type(s) Entry, String ", I'm assuming because I'm calling mid ( an int value ) with an array of strings, although mid really is a reference to the middle index not the actual values stored in the array.

I could potentially completely wrong here and therefore seem stupid :P but I'm pretty confused, any help appreciated.

Community
  • 1
  • 1

1 Answers1

2

The problem is not that you use mid, which is an int, to index an array of Strings. This is perfectly fine. The problem is that you try to use the > operator with Strings.

To compare Strings, you can use compareTo instead of >.

So, instead of:

a[mid] < key

You would use:

a[mid].compareTo(key) < 0
Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • Hey, thanks a lot. Why in the link I provided were they able to use the '>' operator ? – user3443834 Apr 16 '14 at 18:38
  • @user3443834 This operator is defined for the `int` type, as well as some others (`double`, `char`...), but not for `String`s. – Joffrey Apr 16 '14 at 18:39