Java的ArrayList中搜索 [英] Java ArrayList search
问题描述
我有一个的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:GTR
使用 VKL:
不用循环数组。列表(也搜索应不区分大小写,因此,使用 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
)
我怎样才能做到这一点?
How can I do this ?
先谢谢了。
推荐答案
您必须循环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屋!