我正在研究Java应用程序,我正在使用它int ArrayList.
我正在获取当前ArrayList索引,但请指导我如何ArrayList使用for循环获取下一个索引.
我正在尝试使用下面的代码执行此操作,但我得到一个ArrayIndexOutOfbound例外:
ArrayList<Integer> temp1 = new ArrayList<Integer>();
Run Code Online (Sandbox Code Playgroud)
假设arraylist具有以下元素.
temp1={10,20,30}
Run Code Online (Sandbox Code Playgroud)
我们如何使用for循环来实现这一目标:
for(int i=0;i<arraylist.size;i++)<--size is 3
{
int t1=temp1.get(i);
int t2=temp1.get(i+1); // <---here i want next index
}
Run Code Online (Sandbox Code Playgroud)
我想增加1st-10和20 2nd-20和30 3rd-30和10
是否有可能实现这一目标?它适用于任何规模的ArrayList.我愿意采用不同的方法来实现这一目标.
如果要为最后一个索引添加第一个索引值,则应将next position索引用作 - (i+1)%arraylist.size().此外,对于ArrayList大小是一个函数,而不是一个变量.
所以循环将是 -
for(int i=0;i<arraylist.size();i++)<--size is 3
{
int t1=temp1.get(i);
int t2=temp1.get((i+1)%arraylist.size());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1447 次 |
| 最近记录: |