Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching an array and returning an index

 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest. Would the same idea work when trying to return the index of character?

Thanks
 
Rob Spoor
Sheriff
Pie
Posts: 20751
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic