开发者

Searching in unsorted string array

I have this array of strings

private static String[] colorsArray = { "#bde876", "#ff8581", "#ffc472",
    "#faed75", "#a8c9e5", "#999999", "#e开发者_Go百科3a8e5", "#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?


How about

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜