如何获取List中特定项的最后一个索引?

时间:2015-11-11 14:36:11

标签: java list arraylist

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]

2 个答案:

答案 0 :(得分:2)

一个简单的实现方法是检查所需项目是否出现,然后迭代以获取所需项目的索引,如果找到新索引则覆盖先前的索引。最后返回此索引。

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”(谢谢Tom!)。

答案 1 :(得分:0)

您可以使用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;
  }
}

另一种方法是覆盖equals类中的hashCodeShip

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));