Use the for loop to traverse the list in Java

How to use index to iterate list data structure For example, consider a list sentence where each element is a word Can I use the index to step through each word? Something like this –

// sentence defined something like this - List<String>
int size = sentence.size();
for (int i=0; i<size-1; i++)
{
    System.out.println(sentence[i] + " " + sentence[i+1]);
}

Of course, the above code doesn't work, but can you do anything on these lines? As you can see, I want to access two consecutive elements and use iterators, and it starts to get very messy

Solution

You can use the get (I) method instead of [i]:

for (int i=0; i<size-1; i++) {
    System.out.println(sentence.get(i) + " " + sentence.get(i+1));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>