Java Array Question (Noob)

Discussion in 'Mac Programming' started by antoneoh, Nov 1, 2010.

  1. macrumors newbie

    Joined:
    Jun 12, 2007
    #1
    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"};
    
    }
    
    }
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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
     
  3. macrumors 65816

    macsmurf

    Joined:
    Aug 3, 2007
    #3
    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.
     
  4. macrumors 65816

    macsmurf

    Joined:
    Aug 3, 2007
    #4
    sort runs in O(n*log(n)) so the second method is faster than the first.
     
  5. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #5
    Well, sure, if you're only finding one item. =)

    -Lee
     
  6. macrumors 65816

    macsmurf

    Joined:
    Aug 3, 2007
    #6
    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.
     
  7. thread starter macrumors newbie

    Joined:
    Jun 12, 2007
    #7
    Thanks for the help guys
     
  8. macrumors 6502a

    Joined:
    Jun 27, 2010
    #8
    BTW: That is just one string you have there. As opposed to an array of strings.
     

Share This Page