Results 1 to 6 of 6
- 10-07-2008, 03:24 AM #1
[SOLVED] A direct way to get an index from an array?
Gang:
Is there a direct way to get the index of an element from an array (in this case, all elements in the array are different)? Maybe something like the "indexOf" used in strings?. I've searched, but haven't found anything. It sorta lookin like I'm going to have to loop through the array comparing against the array elements.
Thanks,
CJSL
-
You could loop through the array trying to match your object with each item in the array.
- 10-07-2008, 03:56 AM #3
That's what I thought...
That's what I thought. OK... thanks... I'll cook something up and post it.
Thanks,
CJSL
- 10-07-2008, 06:24 AM #4
Sample
Since there doesn't appear to be direct way to obtain the index of an array object, here's a piece of code that can be used to get the object's index:
Java Code:public int getArrayIndex(int[] myArray, obj myObject) { int ArraySize = Array.getLength(myArray);//get the size of the array for (int i = 0; i < ArraySize; i++) { if (intDaPosition[i] == intDaNewPositionNumber) { return(i); } } return(-1);//didn't find what I was looking for }
- The method takes two arguments: the array and the object (int, string, etc) that is to be searched for in the array
- In this case the comparation in the "if" statement is for ints. If strings are to be searched then ".equals" or ".compareTo" should be used. Since I was searching for ints, I used "==" for comparing
- The method returns the index of the object within the array if the object is found. If not found it returns "-1"
- 10-07-2008, 08:57 AM #5
If your array is sorted, you can use java.util.Arrays#binarySearch.
db
- 10-07-2008, 06:10 PM #6
Similar Threads
-
Not direct to localhost:8080/test/index.do and show This is my JSP page?
By techissue2008 in forum Web FrameworksReplies: 0Last Post: 06-07-2008, 10:02 PM -
how direct her/ him to the Sun´s download page?
By willemjav in forum Java AppletsReplies: 1Last Post: 04-17-2008, 05:03 PM -
Help with Flesch Index
By L_22 in forum Advanced JavaReplies: 1Last Post: 03-31-2008, 06:30 PM -
Replacing at an index
By bugger in forum New To JavaReplies: 2Last Post: 01-29-2008, 07:33 AM -
problems with array index
By mary in forum New To JavaReplies: 2Last Post: 08-01-2007, 05:30 PM
Bookmarks