![](/img/trans.png)
[英]How to add elements to a list object by iterating 3 different list objects in java?
[英]How to add elements to an object list in java
public class Bus{
private int seats;
private List<People> currentPeople;
public Bus(int seats){
this.seats = seats;
}
public void passengers(List<People> boarders, List<People> deboarders){
this.currentPeople.remove(deboarders);
this.currentPeople.add(boarders);
}
我正在嘗試創建公交車上的人員列表。 我正在嘗試從列表中刪除 deboarders(下車乘客)並添加寄宿生(登機乘客)。 但是 Java 不允許我將寄宿生添加到 currentPeople 列表中。 People 是一個存儲乘客姓名和票號的類。 這有什么幫助嗎? 我一直試圖解決這個問題幾個小時。
要將對象集合添加到列表中,您需要使用addAll
:
this.currentPeople.addAll(boarders);
要從列表中刪除一組對象,您需要使用removeAll
:
this.currentPeople.removeAll(deboarders);
請注意,為了比較並從列表中刪除正確的元素, removeAll
使用了equals
方法。 所以你應該在你的People
類中實現equals
方法。
編輯:
People 類的equals
方法:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
People people = (People) o;
if (ticketNumber != people.ticketNumber) return false;
return name != null ? name.equals(people.name) : people.name == null;
}
不要忘記初始化currentPeople
列表,否則你會得到NullPointerException
。
將 add 更改為 addAll 並同樣更改為刪除。
正如 Federico 在評論中指出的那樣,假設 People 已經實現了 equals 方法。
嘗試 removeAll() 和 addAll() 方法,因為您將 Collection 作為參數傳遞。
不要忘記在構造函數中行尾的“;”。
this.currentPeople.removeAll(deboarders);
this.currentPeople.addAll(boarders);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.