简体   繁体   中英

java referencing objects in an array

Is there a similar function to indexof() that will search a string array (preferably unsorted) for a string and return it's index? (or maybe ordinate value?)

for example i am trying:

String[] colours= {"Red", "Orange", "Yellow"};

System.out.println("indexOf(Red) = " +
        colours.indexOf("Red"));

...but having no success.

thanks.

AV

ps this will eventually need to work in a 2d array (in case that matters)

String[] colours= {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};

Arrays.asList(colours).indexOf("Red"); // 0

OR
if order doesn't matter then

Arrays.sort(colours);   
Arrays.binarySearch(colours,"Red");//binary search takes sorted[natural order] array as input

For sorted arrays you can use Arrays.binarySearch: http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html

For unsorted arrays Arrays.asList(array).indexOf("String") will do.

However this last method won't be very efficient as the list is going to be scanned sequentially.

Frankly...

int findString(String[] stringArray;String match) {
  for (i=0;i<stringArray.length;++i) {
    if (match.equals(stringArray[i]) return i;
  }
}

will do you just fine. You could have written that in less time than it took to ask the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM