| Author |
Searching an array and returning an index
|
Sam Bluesman
Ranch Hand
Joined: Nov 21, 2004
Posts: 188
|
|
Lets say i have an array called int[] numbers with values [1,2,3]. If i have a variable called calculatedNumber and its value is 2, how do i return the index of that value so that a varibale called calculatedNumberIndex becomes equal to 1? Note that all the values in []numbers will be unique Thanks [ November 09, 2005: Message edited by: Sam Bluesman ]
|
Moosey knows best
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
If the array is sorted, you can use the static java.util.Arrays.binarySearch() functions to do exactly this. If the array is not sorted, though, you just have to do
|
[Jess in Action][AskingGoodQuestions]
|
 |
Sam Bluesman
Ranch Hand
Joined: Nov 21, 2004
Posts: 188
|
|
Hi Ernest. Would the same idea work when trying to return the index of character? Thanks
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
It would work for any type inside the array, as long as you keep in mind that in most cases you should use equals() to compare all non-primitives.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Searching an array and returning an index
|
|
|