在未排序的字符串数组中搜索(Searching in unsorted string array)

编程入门 行业动态 更新时间:2024-10-18 18:24:43
在未排序的字符串数组中搜索(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");

更多推荐

本文发布于:2023-08-07 13:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464516.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   组中   Searching   array   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!