Java ArrayList 搜索 [英] Java ArrayList search
问题描述
我有一个 String
类型的 ArrayList
.我想确定这个 ArrayList
的任何元素是否以指定的字符串开头,如果 ArrayList
包含这个元素,那么我想获取这个元素的索引.另外,我不想循环这个 ArrayList
来获取那个元素的索引.
I have an ArrayList
of type String
. I want to determine whether any element of this ArrayList
starts with a specified string and if the ArrayList
contains this element, then I want to get the index of this element. In addition, I do not want to loop this ArrayList
to get the index of that element.
例如:
ArrayList<String> asd = new ArrayList<String>(); // We have an array list
//We filled the array list
asd.add("abcc trtiou");
asd.add("aiwr hiut qwe");
asd.add("vkl: gtr");
asd.add("aAgiur gfjhg ewru");
现在,我想通过使用 vkl:
而不循环数组列表来获取元素 vkl: gtr
的索引.(搜索也应该不区分大小写,所以,使用 vkl:
和 VkL:
应该给出 vkl: gtr
)
Now, I want to get the index of the element vkl: gtr
by using vkl:
without looping array list.(searching also should be case insensitive, so, using vkl:
and VkL:
should give the index of vkl: gtr
)
我该怎么做?
提前致谢.
推荐答案
你必须循环 ArrayList.您不可能只访问一个索引并保证它就是您要查找的索引.
You have to loop the ArrayList. You cant possibly access just a single index and be guaranteed it is what you're looking for.
此外,如果涉及大量搜索,您应该考虑使用其他数据结构.搜索一个 ArrayList 需要 O(n)
时间,而像红黑树这样的事情可以在 O(log n)
中完成.
Also, you should consider using another data structure if a lot of searching is involved. Searching an ArrayList takes O(n)
time while something like a red-black tree can be done in O(log n)
.
如果您在程序执行之前知道用于定位结构中项目的字符串,请考虑使用 HashMap.您可以访问 O(1)
中的项目.
If you know before program execution the strings used to locate the items in the structure, consider using a HashMap. You can access the items in O(1)
.
如果这些解决方案中没有一个适合您的特定问题,那么我们可以通过您尝试执行的操作来扩展您的答案,我们可以提供更好的答案,说明您如何以最少的搜索时间找到您的项目.
If none of these solutions suit your particular problem expand on your answer with what you're trying to do, we could provide a better answer as to how you'd locate your items with minimal search time.
这篇关于Java ArrayList 搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!