Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Searching in unsorted string array

I have this array of strings

private static String[] colorsArray = { "#bde876", "#ff8581", "#ffc472",
    "#faed75", "#a8c9e5", "#999999", "#e3a8e5", "#dddddd", "#fc603c",
    "#ffcc00", "#74e8d4", "#3cd6fc" };

Then I have this method

public static int getColorByString(String color) {
    return Arrays.binarySearch(colorsArray, color);
}

When I call getColorByString("#ff8581"); it gives me -13 as result.

If I understood well, it means that the element is not contained in my array.

What am I doing wrong? How can I make it work?

EDIT

I just realized the array has to be sorted. The problem is I can't sort it, because I need to map the strings to a specific index.

So now the question becomes, is there any method that performs a linear search or do I have to write it?

Upvotes: 1

Views: 3151

Answers (1)

tim_wonil
tim_wonil

Reputation: 15786

How about

Arrays.<String>asList(colorArray).indexOf("#ff8581");

Upvotes: 4

Related Questions