简体   繁体   English

ArrayList查找第一个和最后一个元素

[英]ArrayList Find First and Last Element

Good Evening, 晚上好,

I have an ArrayList (instantiated as ld_data) and I iterate forward and back looking / displaying to the user the element data. 我有一个ArrayList(实例化为ld_data),我向前和向后迭代查看/向用户显示元素数据。 In this process I need to know when I am at the first element and the last. 在这个过程中,我需要知道我何时处于第一个元素和最后一个元素。 Detecting when I am at the last element I do as such: 检测我何时处于最后一个元素:

if((index + 1) <= ld_data.size())
{
    ....
}

This works because the size property also is the upper bound of the ArrayList. 这是因为size属性也是ArrayList的上限。 However detecting when I am at the first element is not as easy for me. 然而,检测我何时处于第一个元素对我来说并不容易。 The best I've been able to figure out is this which seems rather lame....but it works. 我能够弄清楚的最好的是这看起来相当蹩脚......但它确实有效。

if((index - 1) >= (ld_data.size() - ld_data.size()))
{
    ....
}

In the C# .NET world we have ArrayList.UpperBound or ArrayList.LowerBound is there something similiar in Java? 在C#.NET世界中,我们有ArrayList.UpperBound或ArrayList.LowerBound在Java中有类似的东西吗?

JB JB

EDIT: Further details. 编辑:更多细节。 So for more information I am bound to a ListView. 因此,对于更多信息,我绑定到ListView。 So when the user has scrolled to the first element of the list I want to show a msg "At start of list" and when they reach the end show "End of list". 因此,当用户滚动到列表的第一个元素时,我想显示一个消息“在列表的开头”,当它们到达结束时显示“列表结束”。 I know there is a scrollbar that makes this obvious I'm just trying to give an example of what I'm doing. 我知道有一个滚动条使这显而易见我只是想举例说明我在做什么。 So this check occurs in the "OnScroll" event. 因此,此检查发生在“OnScroll”事件中。

Its always advised to use Iterators or ListIterator to iterate through a list. 始终建议使用IteratorsListIterator迭代列表。 Using the list size as reference does not workout when you are modifying the list data (removing or inserting elements). 在修改列表数据(删除或插入元素)时,使用列表大小作为参考不会进行锻炼。

Iterator - allow the caller to iterate through a list in one direction and remove elements from the underlying collection during the iteration with well-defined semantics 迭代器 - 允许调用者在一个方向上遍历列表,并在迭代期间使用明确定义的语义从底层集合中删除元素

You can use a ListIterator to iterate through the list. 您可以使用ListIterator迭代列表。 A ListIterator allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. ListIterator允许程序员在任一方向遍历列表,在迭代期间修改列表,并获取迭代器在列表中的当前位置。 You can refer the below example. 您可以参考以下示例。

ArrayList<String> list = new ArrayList<String>();
    ListIterator<String> iterator = list.listIterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
        ...
        ...
        System.out.println(iterator.previous());
        if(!iterator.hasPrevious()){
            System.out.println("at start of the list");
        }else if(!iterator.hasNext()){
            System.out.println("at end of the list");
        }

    }

This is just an example showing the usage of a ListIterator , please analyze what your requirement is and implement as required. 这只是一个显示ListIterator用法的示例,请分析您的要求并按要求实施。

List<YourData> list = new ArrayList<YourData>();

for(int index=0; index < list.size(); index++) {

    YourData currElement = list.get(index);

    if(index == 0) {
        //currElement is the first element
    }

    if(index == list.size() - 1) {
         //currElement is the last element
    }
}

只需检查索引是否等于0.第一个元素始终位于此索引中。

ArrayList s always have a bottom index of 0. So if (index > 0) { // okay to decrement } will work fine. ArrayList的底部索引总是为0.所以if (index > 0) { // okay to decrement }可以正常工作。

You can also request a list iterator 您还可以请求列表迭代器

ListIterator<Item> i = ld_data.listIterator();

if (i.hasNext()) {
    Item item = i.next();
}

// and

if (i.hasPrevious()) {
    Item item = i.previous();
}

It appears you want to abstract away the logic to deal with the first, last, and anything that comes in between in different ways. 看起来你想抽象出逻辑来处理第一个,最后一个,以及以不同方式介于两者之间的任何东西。

You can do it by defining a destructuring class as shown below: 你可以通过定义一个解构类来实现,如下所示:

import java.util.*;

abstract class EndsDestructurer<A, B> {
  public abstract B first(A a);
  public abstract B intermediate(A a);
  public abstract B last(A a);

  public List<B> apply(List<A> xs) {
    int i = 0;
    int lastIndex = xs.size() - 1;
    List<B> ys = new ArrayList<B>();
    for (A x : xs) {
      if (i == 0) ys.add(first(x));
      else if (i == lastIndex) ys.add(last(x));
      else ys.add(intermediate(x));
      i++;
    }
    return ys;
  }
}

Use: 使用:

EndsDestructurer<Object, String> stringer = 
  new EndsDestructurer<Object, String>() {
    public String first(Object o) { return "first: " + o; }
    public String intermediate(Object o) { return "intermediate: " + o; }
    public String last(Object o) { return "last: " + o; }
  };

List<Object> xs = Arrays.<Object>asList(90, "hello", 5.6, 12, "namaste", false);
System.out.println(stringer.apply(xs));

The above prints: 以上打印:
[first: 90, intermediate: hello, intermediate: 5.6, intermediate: 12, intermediate: namaste, last: false] . [first: 90, intermediate: hello, intermediate: 5.6, intermediate: 12, intermediate: namaste, last: false]

I would suggest you to use Google Guava for that. 我建议你使用谷歌番石榴 The getLast method will throw NoSuchElementException if the list is empty: 如果列表为空,则getLast方法将抛出NoSuchElementException

lastElement = Iterables.getLast(iterableList);

And to get the first element: 并获得第一个元素:

firstElement = Iterables.getFirst(iterable, defaultValue)

For more information about Java Collections, check it out . 有关Java Collections的更多信息, 请查看它

Your index is always going to be 0 - myList.size() -1. 你的索引总是0 - myList.size() - 1。 I suspect maybe I'm not understanding your question because this seems self evident. 我怀疑也许我不理解你的问题,因为这似乎是不言而喻的。

AFAIK, ArrayList class have no such method to give the first and last element of it's object. AFAIK, ArrayList类没有这样的方法来给出它的对象的first and last element


You can write some code like, 你可以写一些代码,比如

ArrayList<String> arr = new ArrayList<String>();
int size = arr.size();
if(size==0)
{
    // no data
}
else if(size == 1)
{
    // first = arr.get(0);
    // last = arr.get(0);
}
else
{
    // first = arr.get(0);
    // last = arr.get(size-1);
}

In the C# .NET world we have ArrayList.UpperBound or ArrayList.LowerBound is there something similiar in Java? 在C#.NET世界中,我们有ArrayList.UpperBound或ArrayList.LowerBound在Java中有类似的东西吗?

In the Java world, the first element of any indexable collection always has offset zero, so "lower bound" and "upper bound" methods would be redundant. 在Java世界中,任何可索引集合的第一个元素始终具有偏移零,因此“下限”和“上限”方法将是多余的。

Just use the constant 0 . 只需使用常数0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM