wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Searching an array and returning an index Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Searching an array and returning an index" Watch "Searching an array and returning an index" New topic
Author

Searching an array and returning an index

Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191
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: 24183
    
  34

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: 191
Hi Ernest. Would the same idea work when trying to return the index of character?

Thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Searching an array and returning an index