使用for循环遍历Java中的列表 [英] iterating through list in java using for loop

查看:422
本文介绍了使用for循环遍历Java中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用索引遍历列表数据结构?例如,考虑一个列表形式的句子,每个元素是一个单词。我可以使用索引来查看每个单词吗?像这样的东西 -

  //定义了这样的句子 -  List< String> 
int size = sentence.size();
for(int i = 0; i< size-1; i ++)
{
System.out.println(sentence [i] ++ sentence [i + 1]);





$ b

ofcourse上面的代码不起作用,但可以做些什么那些线?正如你所看到的,我想访问这两个连续的元素,并使用迭代器,它开始变得非常混乱。解析方案

你可以使用 get(i)方法而不是 [i]

  for(int i = 0; i< 1; i ++){
System.out.println(sentence.get(i)++ sentence获得(I + 1));
}


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.

解决方案

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

这篇关于使用for循环遍历Java中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆