在未排序的字符串数组中搜索(Searching in unsorted string array)
我有这个字符串数组
private static String[] colorsArray = { "#bde876", "#ff8581", "#ffc472", "#faed75", "#a8c9e5", "#999999", "#e3a8e5", "#dddddd", "#fc603c", "#ffcc00", "#74e8d4", "#3cd6fc" };然后我有这个方法
public static int getColorByString(String color) { return Arrays.binarySearch(colorsArray, color); }当我调用getColorByString("#ff8581"); 它给了我-13结果。
如果我理解得很好,这意味着该元素不包含在我的数组中。
我究竟做错了什么? 我怎样才能使它工作?
编辑
我刚刚意识到数组必须排序。 问题是我无法对其进行排序,因为我需要将字符串映射到特定索引。
所以现在问题变成了,是否存在执行线性搜索的方法或是否必须编写它?
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?
最满意答案
怎么样
Arrays.<String>asList(colorArray).indexOf("#ff8581");How about
Arrays.<String>asList(colorArray).indexOf("#ff8581");更多推荐
发布评论