1

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?

3
  • Just a note, I realise that your array is declared as static. That may have some undesired effect on what you want to do unless you are sure that it is used in a thread-safe way. Commented Aug 3, 2010 at 0:07
  • @tim_wonil Does it helps it never gets modified? Commented Aug 3, 2010 at 0:19
  • yes, if it never gets modified, I believe it is safe enough for our purpose here. :-) Commented Aug 3, 2010 at 0:23

1 Answer 1

4

How about

Arrays.<String>asList(colorArray).indexOf("#ff8581");
Sign up to request clarification or add additional context in comments.

1 Comment

While you are at it, you might consider making your String[] into a List<String>. This gives you access to more methods easily, and prevents the overhead of creating new List objects every time you want to use one of those methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.