Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

antoneoh

macrumors newbie
Original poster
Jun 12, 2007
21
0
Hello all, I'm a noob java guy and I need some assistance.
I'm trying to make a statement to check if a variable is inside an array. Like if strawberry is in candyArr1 array, the result would be true. Thanks.


Code:
public class Candy{

public static void main (String args[]){

String[] candyArr1 = {"butterscotch, marshmallow, strawberry"};

}

}
 
Are you asking if there is a method that will do this for you, or how you would search for this yourself?

For the prior, java.utils.Arrays has a sort method, and a binarySearch method, which you could use to sort then search the array.
http://download.oracle.com/javase/6...ySearch(java.lang.Object[], java.lang.Object)

If the latter, for each would be a way to do this (though slow/inefficient). It would look like:

Code:
boolean containsString (String[] searchList,String toFind) {
  if(searchList == null || toFind == null) return false;
  for(String single : searchList) {
    if(single.equals(toFind)) return true;
  }
  return false;
}

I haven't compiled or tested that code, and some more robust error-checking is probably in order, but it would look something like that. This is O(n), but doesn't require sorting.

-Lee
 
This probably won't help you but collections in Java has a contains() method. That means that this will work:

Code:
String[] candyArr1 = {"butterscotch", "marshmallow", "strawberry"};
System.out.println(Arrays.asList(candyArr1).contains("marshmallow"));

Anyway, the above is probably confusing so you should instead iterate through the array as Lee explains.
 
Are you asking if there is a method that will do this for you, or how you would search for this yourself?

For the prior, java.utils.Arrays has a sort method, and a binarySearch method, which you could use to sort then search the array.
http://download.oracle.com/javase/6...ySearch(java.lang.Object[], java.lang.Object)

If the latter, for each would be a way to do this (though slow/inefficient). It would look like: <snip>

I haven't compiled or tested that code, and some more robust error-checking is probably in order, but it would look something like that. This is O(n), but doesn't require sorting.

-Lee

sort runs in O(n*log(n)) so the second method is faster than the first.
 
Well, sure, if you're only finding one item. =)

-Lee

Well, you have a point but big oh doesn't care if you're finding one or more items as long as you're not finding a number of items dependent on n. Finding three items would still be O(n). Then again, big oh cannot directly be viewed as a measure of speed.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.