Java 如何获取列表中特定项的最后一个索引?
如何获取特定shipId列表中最后添加的项目。Fox示例shipId1最后添加的项目在这里Java 如何获取列表中特定项的最后一个索引?,java,list,arraylist,Java,List,Arraylist,如何获取特定shipId列表中最后添加的项目。Fox示例shipId1最后添加的项目在这里[shipID:1 position:30]一个简单的实现是检查所需项目的任何出现情况,然后迭代获取所需项目的索引,如果找到新的索引,则覆盖以前的索引。在末尾返回此索引 [shipID: 1 position: 10] [shipID: 1 position: 20] [shipID: 2 position: 10] [shipID: 1 position: 30] [shipID: 2 position:
[shipID:1 position:30]
一个简单的实现是检查所需项目的任何出现情况,然后迭代获取所需项目的索引,如果找到新的索引,则覆盖以前的索引。在末尾返回此索引
[shipID: 1 position: 10]
[shipID: 1 position: 20]
[shipID: 2 position: 10]
[shipID: 1 position: 30]
[shipID: 2 position: 20]
编辑以添加检查列表中是否不存在“desiredStringToCheck”(感谢Tom!)。您可以使用
列表迭代器反向迭代数据:
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
然后只需使用List.lastIndexOf
:
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;
}
}
你想过这个问题吗?谢谢!这就行了!是的,这是一节课。所以他需要写几个getter。为什么不向后迭代,找到匹配的事件后返回呢。。我没想到。现在将使用向后迭代更新我的解决方案。谢谢Andy。如果找不到搜索的元素,是否确实要返回索引0
?
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
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;
}
}
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;
}
}
ships.lastIndexOf(new Ship(1, 10));