• Post Reply Bookmark Topic Watch Topic
  • New Topic

location of array element  RSS feed

 
Anandh Ramesh
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

i have a string array. i need to find out the location of a particular element in the array. how do i go about it?

any help is appreciated.
 
Luciano Mantuaneli
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is many approaches. I'll give you two.
1) If your String array is sorted, you can use the java.util.Arrays' binarySearch method:


2)You can use an temporary java.util.List object created from your array and use the indexOf method


Hope it heps you!

PS.: Note that, in both cases, if the position variable hava an negative value, it means that myString wasn't found in myStringArray array
[ December 04, 2006: Message edited by: Luciano Mantuaneli ]
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This will give you character you want according to the <index> you pass in charAt method of String class.



API Reference Doc
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I misunderstood the question.

You can follow Luciano Mantuaneli advice.

Thanks.
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you didn't know the API's, you could search the array yourself:



Of course, if your array was already sorted and your array had a huge number of elements the binary search would be faster, since it is order log(n) and searching the whole array, as I've done here, is order(n).
[ December 05, 2006: Message edited by: Kaydell Leavitt ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!