我有一个列表如下:
List<String> x = new ArrayList<String>();
x.add("Date : Jul 15, 2010 Income : 8500 Expenses : 0");
x.add("Date : Aug 23, 2010 Income : 0 Expenses : 6500");
x.add("Date : Jul 15, 2010 Income : 0 Expenses : 4500");
我现在想按如下方式访问这些索引:
int index1 = x.indexOf("Date : Aug 23, 2010");
//1
int index2 = x.indexOf("Date : Jul 15, 2010");
//0
int index3 = x.lastIndexOf("Date : Jul 15, 2010");
//2
有什么帮助吗?提前致谢。
这是我一直在寻找的解决方案:
// traverse the List forward so as to get the first index
private static int getFirstIndex(List<String> theList, String toFind) {
for (int i = 0; i < theList.size(); i++) {
if (theList.get(i).startsWith(toFind)) {
return i;
}
}
return -1;
}
// traverse the List backwards so as to get the last index
private static int getLastIndex(List<String> theList, String toFind) {
for (int i = theList.size() - 1; i >= 0; i--) {
if (theList.get(i).startsWith(toFind)) {
return i;
}
}
return -1;
}
这两种方法将完全满足我想要的要求。谢谢大家!