How does one iterate through a list datastructure using indices. For example consider a sentence in form a list with each element being a word. Can I step through each word using the index? Something like this --
// sentence defined something like this - List
int size = sentence.size();
for (int i=0; i
{
System.out.println(sentence[i] + " " + sentence[i+1]);
}
ofcourse the above code doesn't work but is it possible to do something on those lines? As you can see, I want to access the two consecutive elements and using iterators, it starts becoming really messy.
解决方案
You can use the get(i) method instead of [i]:
for (int i=0; i
System.out.println(sentence.get(i) + " " + sentence.get(i+1));
}