This is a weird problem, but Im certain its not to weird to some of you all. My task is to return the first index of this vector where obj can be found, starting from the first element and moving right through this vector. Return -1 if obj is not found in this vector. Throw IndexOutOfBoundsException if start is outside [0, myCt), or if vector is empty.
my code in the main method to call this method is:
And my code (current) of the indexOf(obj, start) is as follows:
The problem is that when indexOf tries to run from start to myArray.length I get the count of 6,7, null because the array capacity is 8 and the last value is not filled yet, thus giving me a NullPointerException when the obj does not equal the obj that I cast into the method. In this instance my array looks like this: < 2, 3, 4, 5, 6, 7 > (cap: 8) And my start position is 4 and I am looking for a 3. The method works if I start from i=0 or 1 but not if I go beyond that. Is there anyway to modify the indexOf method to not look at the null space and go ahead and return -1 instead of a catch exception? In other words can I just decrement myCt(which is my capacity for the array) and return -1 instead of getting the null? Thanks for the help Steve [ January 28, 2004: Message edited by: Steve Wysocki ]
you could try comparing your object to null and return -1 if it is equal:
just before you test for myArray[i].equals (remember though, you can't have any "holes" in your data structure if you do this! If you want that, use "continue" instead of "return -1") HTH [ January 28, 2004: Message edited by: Timmy Marks ]
Joined: Mar 02, 2003
yeah, I guess that would be legal. I know that will work, but is there any other way? Thanks for the reply bro. Steve
Joined: Dec 01, 2003
You could also use myCt as your loop limit instead of the array length
First, this takes the test for a valid "start" outside the loop; there is no need to check it every time through the loop. [A good optimizing compiler would fix this, but why risk it ...]. If "obj" is null don't do the test, which will result in a return of "-1". Now inside the loop you know that obj is non null, so you can safely call the "equals()" method on obj, and it doesn't matter if the array element is null or not. Safe and simple.