iterating through list in java using for loop

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<String>
int size = sentence.size();
for (int i=0; i<size-1; 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.

Answers


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

List instances are not the same as arrays. They have specific methods for obtaining items at certain indexes. Try this:

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

Now if you had an array (e.g. String[] sentence = new String[]{"hello", "there"}), what you had would work fine.

As a side note, Java has a for-each loop that can be used on both arrays and Lists:

for (String s : sentence) {
    // do something
}

Of course, this can't be used in your case because you're accessing elements at multiple indexes in each iteration of your loop - but it's important to know that something like this exists.


Need Your Help

is there a way NicEditor be on a subfolder and not outside the demo page folder?

php

Hello I just want to know if I can put it on a subfolder instead ? When I tried to put it on subfolder or within the same folder of my page, it displays normal textare. But whenever I put it outsid...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.