Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Searching an array and returning an index  RSS feed

 
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
Sheriff
Posts: 24217
38
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
Posts: 21019
85
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.
 
You have to be odd to be #1 - Seuss. An odd little ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!