简体   繁体   中英

How to get the last index of a specific item in a List?

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

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

The ships list is:

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

How can I get the last added item in the list of a specific shipId. Fox example the last added item of shipId1 is here [shipID: 1 position: 30]

An easy implementation would be to check for any occurrence of the desired item, then iterate through to get the indexes of the desired item, overwriting the previous index if a new one is found. Return this index at the end.

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

An alternative solution (suggested by Andy, thanks!) is to iterate backwards and get the first occurrence of the desired item and return this value.

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

Edited to add checking for if the "desiredStringToCheck" doesn't exist in the list (Thanks Tom!).

You can iterate through the data backwards using 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;
  }
}

An alternative way is to override equals and hashCode in your Ship class:

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

Then just use List.lastIndexOf :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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