开发者

Get objects' index in a Java List

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 docume开发者_如何学JAVAntation 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 every index?

Thanks!


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.

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.


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


An alternative brute force approach that will also find all null indexes:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜