【问题标题】:How to get the last index of a specific item in a List?如何获取列表中特定项目的最后一个索引?
【发布时间】:2015-11-11 14:36:11
【问题描述】:
public class Ship
{
   private int shipId;
   private int position;
}

public class MessageOfShip{
    private List<Ship> ships=new ArrayList<Ship>();
}

船名单是:

[shipID: 1 position: 10]
[shipID: 1 position: 20]
[shipID: 2 position: 10]
[shipID: 1 position: 30]
[shipID: 2 position: 20]

如何获取特定 shipId 列表中最后添加的项目。 Fox示例shipId1最后添加的项目在这里[shipID: 1 position: 30]

【问题讨论】:

  • 你有没有想过这个问题?

标签: java list arraylist


【解决方案1】:

一个简单的实现是检查所需项目的任何出现,然后遍历以获取所需项目的索引,如果找到新的则覆盖之前的索引。最后返回这个索引。

int desiredIndex = -1;
for (int i = 0; i < ships.size(); i++) {
    if (ships.get(i).equals("desiredStringToCheck") {  //it may not necessarily be a string
        desiredIndex = i;
    }
}
return desiredIndex;     //-1 signifies that the string is not found

另一种解决方案(由 Andy 建议,谢谢!)是向后迭代并获取所需项目的第一次出现并返回此值。

for (int i = (ships.size() - 1); i >= 0; i--) {
    if (ships.get(i).equals("desiredStringToCheck") {  //it may not necessarily be a string
        return i;
    }
}
return -1;       //If it doesn't return in the loop, meaning the string is not in the list

编辑添加检查列表中是否不存在“desiredStringToCheck”(感谢汤姆!)。

【讨论】:

  • 谢谢!这样就可以了!
  • 是的,这是一门课。所以他需要写几个getter。
  • 为什么不直接向后迭代,一旦找到匹配项就返回?
  • 我.. 没想到。现在将使用向后迭代更新我的解决方案。谢谢安迪。
  • 如果找不到搜索到的元素,确定要返回索引0吗?
【解决方案2】:

您可以使用ListIterator 向后遍历数据:

ListIterator<Ship> it = ships.listIterator(ships.size());
while (it.hasPrevious()) {
  int index = it.previousIndex();
  Ship previous = it.previous();
  if (/* somehow compare previous to the thing you are looking for */) {
    return index;
  }
}

另一种方法是在 Ship 类中覆盖 equalshashCode

public class Ship
{
   private int shipId;
   private int position;

   @Override public int hashCode() {
     return Objects.hashCode(shipId, position);
   }

   @Override public boolean equals(Object other) {
     if (other == this) {
       return true;
     }
     if (other instanceof Ship) {
       Ship o = (Ship) other;
       return shipId == o.shipId && position == o.position;
     }
     return false;
   }
}

那就用List.lastIndexOf:

ships.lastIndexOf(new Ship(1, 10));

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2022-06-23
    • 2022-11-23
    • 2023-03-14
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    相关资源
    最近更新 更多