在 Java 列表中获取对象的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5131600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get objects' index in a Java List
提问by strange quark
I have a list of strings in my (Android) Java program, and I need to get the index of an object in the list. The problem is, I can only find documentation on how to find the first and last index of an object. What if I have 3 or more of the same object in my list? How can I find everyindex?
我的(Android)Java 程序中有一个字符串列表,我需要获取列表中某个对象的索引。问题是,我只能找到有关如何查找对象的第一个和最后一个索引的文档。如果我的列表中有 3 个或更多相同的对象怎么办?我怎样才能找到每个索引?
Thanks!
谢谢!
回答by andersoj
You need to do a brute force search:
您需要进行蛮力搜索:
static <T> List<Integer> indexesOf(List<T> source, T target)
{
final List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < source.size(); i++) {
if (source.get(i).equals(target)) { indexes.add(i); }
}
return indexes;
}
Note that this is not necessarily the most efficient approach. Depending on the context and the types/sizes of lists, you might need to do some serious optimizations. The point is, if you need every index (and know nothing about the structure of the list contents), then you need to do a deathmarch through every item for at best O(n) cost.
请注意,这不一定是最有效的方法。根据上下文和列表的类型/大小,您可能需要进行一些认真的优化。关键是,如果您需要每个索引(并且对列表内容的结构一无所知),那么您需要以最佳的 O(n) 成本对每个项目进行一次死亡之旅。
Depending on the type of the underlying list, get(i)
may be O(1) (ArrayList
) or O(n) (LinkedList
), so this COULD blow up to a O(n2) implementation. You could copy to an ArrayList
, or you could walk the LinkedList
incrementing an index counter manually.
根据底层列表的类型,get(i)
可能是 O(1) ( ArrayList
) 或 O(n) ( LinkedList
),所以这可能会爆炸到 O(n 2) 实现。您可以复制到ArrayList
,或者您可以LinkedList
手动增加索引计数器。
回答by Javanator
If documentation is not helping me in my logic in this situation i would have gone for a raw approach for Traversing the list in a loop and saving the index where i found a match
如果文档在这种情况下不能帮助我解决逻辑问题,我会采用原始方法在循环中遍历列表并保存找到匹配项的索引
ArrayList<String> obj = new ArrayList<String>();
obj.add("Test Data"): // fill the list with your data
String dataToFind = "Hello";
ArrayList<Integer> intArray = new ArrayList<Integer>();
for(int i = 0 ; i<obj.size() ; i++)
{
if(obj.get(i).equals(dataToFind)) intArray.add(i);
}
now intArray would have contained all the index of matched element in the list
回答by Ted Hopp
An alternative brute force approach that will also find all null
indexes:
另一种蛮力方法也可以找到所有null
索引:
static List<Integer> indexesOf(List<?> list, Object target) {
final List<Integer> indexes = new ArrayList<Integer>();
int offset = 0;
for (int i = list.indexOf(target); i != -1; i = list.indexOf(target)) {
indexes.add(i + offset);
list = list.subList(i + 1, list.size());
offset += i + 1;
}
return indexes;
}