从ArrayList中选择next和previous元素选择的值

时间:2016-01-13 07:47:54

标签: java android arraylist

在我的Android应用程序中,我希望获得ArrayList所选值的所有前后元素。我正在使用以下代码,但它不起作用。

ListIterator<Integer> iterator = photoall_id.listIterator();
while(iterator.hasNext())
{
    new  GetImage().execute(url);
    System.out.println(iterator.next());
    System.out.println(iterator.previous());
}

这反复给出random个值。我想从ArrayList的选定位置获取数据。

2 个答案:

答案 0 :(得分:0)

当您打电话给Iterator.previous()进行打印时,您必须再次调用Iterator.next(),否则您可能会无限循环堆叠。

顺便说一句,最简单的解决方案是使用索引:

List<Integer> photoall_id= new ArrayList<Integer>();

int mySelectedId= 3;
int indexOfSelectedId = photoall_id.indexOf(mySelectedId);
if(indexOfSelectedId < 0)
    return; //your value is not in the list
//Print previous values
for(int i = 0; i < indexOfSelectedId ; i++)
{
    System.out.println(photoall_id.get(i));
}
//Print next values
for(int i = indexOfSelectedId + 1 ; i < photoall_id.size(); i++)
{
    System.out.println(photoall_id.get(i));
}

或只在一个cicle中:

for(int i = 0 ; i < photoall_id.size(); i++)
{
    if(i != indexOfSelectedId)
       System.out.println(photoall_id.get(i));
}

答案 1 :(得分:0)

当您next()后跟previous()时,您的iterator指针保持在同一位置。见documentation

  

请注意,对next和previous的交替调用将重复返回相同的元素。

我对此的建议是退后一步(previous())并向前迈出两步(next())。

ListIterator<Integer> iterator = photoall_id.listIterator();
while(iterator.hasNext())
{
    new  GetImage().execute(url);
    if(iterator.hasPrevious())
    {
        System.out.println(iterator.previous());
        iterator.next(); //Coming back to current position
        System.out.println(iterator.next()); // to next to current
    }
    else
    {
        System.out.println(iterator.next());
    }
}

希望这对你有所帮助。

相关问题