| Author |
array . contains () ???
|
Jan Groth
Ranch Hand
Joined: Feb 03, 2004
Posts: 456
|
|
hello, i have an array of int's. thought its a one-liner to check if a given int is contained in that array. but it isn't. or am i blind? any ideas appreceated, jan
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12911
|
|
If the array is sorted, you could use java.util.Arrays.binarySearch(array, key). But if the array isn't sorted, that won't work. Ofcourse you could sort it using java.util.Arrays.sort(array).
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Jan Groth
Ranch Hand
Joined: Feb 03, 2004
Posts: 456
|
|
hi jesper, i was already checking the javadoc, but to be honest i did not fully understand the documentation of the return value of binarySearch:
Returns: index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
are we sure that a returned value >0 implies "found" ? i'm not :-) cheers, jan
|
 |
Jan Groth
Ranch Hand
Joined: Feb 03, 2004
Posts: 456
|
|
Note that this guarantees that the return value will be >= 0 if and only if the key is found.
stupid me.
|
 |
Ankur Sharma
Ranch Hand
Joined: Dec 27, 2005
Posts: 1234
|
|
Originally posted by Jan Groth: hi jesper, i was already checking the javadoc, but to be honest i did not fully understand the documentation of the return value of binarySearch: are we sure that a returned value >0 implies "found" ? i'm not :-)
If you have read that then do it again and carefully read last line.
index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
. Hoep your doubts would be clear now. Please let us know if there are any issues. [ September 29, 2006: Message edited by: Ankur Sharma ] [ September 29, 2006: Message edited by: Ankur Sharma ]
|
The Best way to predict your future is to create it
Ankur Sharma
|
 |
 |
|
|
subject: array . contains () ???
|
|
|