[英]How to remove an object from a linked list in java
我有一個名為seatList的鏈表,由Seat對象組成,如此設置......
public class Seat {
int row, col;
char type;
Seat(int row, int col, char type){
this.row = row;
this.col = col;
this.type = type;
}
String printSeat(){
return "(" + row + ", " + col + ", " + type + ")";
}
}
當我嘗試通過創建一個新的座位對象並將其存儲在一個名為集合的單獨鏈接列表中來刪除具有相同屬性的席位時,它們不會從鏈接列表中刪除。
LinkedList<Seat> collection = new LinkedList();
for (int q : indexToRemove){
collection.add(new Seat(seatList.get(q).row, seatList.get(q).col, seatList.get(q).type));
}
for (Seat s : collection){
if (seatList.contains(s)){
println("true");
seatList.remove(s);
}
}
if (orders.get(indexes.get(index)).seatList.isEmpty()){
orders.remove((int)indexes.get(index));
}
理由是不同的:鏈接問題談論改變你正在迭代的列表,如csm_dev所述
要從列表中刪除對象,您必須使用Iterator並在迭代器上調用remove()示例:
Iterator<Seat> collection = seatList.iterator();
while (collection.hasNext())
{
Seat element = collection.next();
//some condition on your object "element"
collection.remove();
}
並且不要忘記定義hashCode / equals方法邏輯來比較你的Seat對象
你必須使用Iterator :
Scanner scr= new Scanner(System.in);
System.out.print("Enter Seat Row number to delete: ");
int row = scr.nextInt();
for (Iterator<Seat> iter = list.iterator(); iter.hasNext();) {
Seat data = iter.next();
if (data.getRow() == row) {
iter.remove();
}
}
你必須在上課時添加setter和getter。
LinkedList和其他列表實現使用equals()方法來檢查對象是否存在於列表中。 由於你沒有實現equals()方法,java將使用Object類提供的實現,這非常粗糙,對你不起作用。
你需要實現equals()方法並給jvm一種方法來查看座位的2個對象是否相同。
如果你真的不需要創建新的對象添加到collection
列表中,您可以添加從對象seatList
和第二for
你的代碼片段會從列表中刪除的對象。
for (int q : indexToRemove){
collection.add(seatList.get(q));
}
當您check
天氣列表是否包含對象時,使用對象的equals()
方法,您應該與hashCode()
方法一起實現它以獲得所需的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.