【问题标题】:Select next and previous element from ArrayList selected value从 ArrayList 选定值中选择下一个和上一个元素
【发布时间】:2016-04-18 02:16:18
【问题描述】:

在我的 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的选定位置获取数据。

【问题讨论】:

  • 为什么在访问 ArrayList 时不使用索引?
  • 我同意@MustansarSaeed,只需使用循环并使用list.get(i-1)list.get(i+1) 访问元素。
  • 请给我详细的
  • @krishna 看看我的回答

标签: java android arraylist


【解决方案1】:

当您调用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));
}

或仅在一个循环中:

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

【讨论】:

  • 重复获取元素
  • 你的重复是什么意思?我真的不明白你想要什么
【解决方案2】:

当您转到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());
    }
}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2015-01-14
    • 2012-06-13
    相关资源
    最近更新 更多