抱歉,這已經完成了,但我真的很難實作這個問題的解決方案,而且我對 Java 還是很陌生。
我需要能夠呼叫一個基本上允許將 Person 物件添加到串列中的方法。該方法需要檢查該人是否已經在串列中。它需要按名字執行檢查 - 我知道實際上這看起來很愚蠢,但在這種特定情況下我需要能夠做到這一點。
然后該串列需要對類可用,以便稍后可以呼叫 print list of names 方法。
我在嘗試實施解決方案時遇到的主要問題是“ConcurrentModificationException”,這是可以理解的,因為我一直在嘗試在每個回圈的中間更新串列。
因此,我提出了以下解決方案來防止“ConcurrentModificationException”,但我的解決方案無法正常作業并且似乎過于復雜 - 請參閱以下方法代碼片段:
public void addPerson(Person aPerson) {
// tempPersons list for temporarily storing Person objects
tempPersons = new ArrayList<>();
// if persons list is initially empty, add aPerson object to it
if (persons.isEmpty()) {
persons.add(aPerson);
}
// if persons list is not initially empty
if (!persons.isEmpty()) {
// loop through persons list
for (Person anotherPerson : persons) {
// if persons list anotherPerson first name is the same as the aPerson first name, print message
if (anotherPerson.getFirstName().equals(aPerson.getFirstName())) {
System.out.println("The Person " aPerson.getFirstName()
" is already entered in the list");
}
// otherwise add the aPerson object to the tempPersons list
else {
tempPersons.add(aPerson);
}
}
// once out of loop, add the tempPersons list to the racers list
persons.addAll(tempPersons);
// create new tempPersons2 list based on a hashset of the persons list so there are no duplicates
List<Person> tempPersons2 = new ArrayList<>(
new HashSet<>(persons));
// assign tempPersons2 list without duplicates to persons list
persons = tempPersons2;
}
}
因此,例如,如果我使用唯一和重復物件(aPerson 引數)的混合分別呼叫上述 addPerson 方法 4 次,則該方法正確識別那里已經有一個具有相同名字的物件,但人員串列似乎總是最終在那里有一個重復的物件(名字),例如,如果我有以下物件:
Person1 名字 = Bob
Person2 名字 = Jan
Person3 名字 = Bob
Person4 名字 = Ann
然后我分別呼叫以下方法 4 次:
addPerson(Person1);
addPerson(Person2);
addPerson(Person3);
addPerson(Person4);
當我呼叫列印方法時,我得到以下輸出:
人 Bob 已在串列中輸入
簡
安
鮑勃
鮑勃
我期望以下內容:
人 Bob 已在串列中輸入
簡
安
鮑勃
為所有的華夫餅道歉,對你們大多數人來說,這可能是一個非常簡單的解決方案,但我已經堅持了幾天。如果有人可以根據我提供的示例提供一個簡單的解決方案,將不勝感激?
可以在此處找到類似的文章,但我仍在苦苦掙扎。
在迭代期間向集合中添加元素
uj5u.com熱心網友回復:
無需過多更改代碼:
public void addPerson(Person person) {
// The guard is more or less a premature optimization and should be removed.
if (persons.isEmpty()) {
persons.add(person);
return;
}
for (Person anotherPerson : persons) {
if (anotherPerson.getFirstName().equals(person.getFirstName())) {
System.out.println("The Person " person.getFirstName()
" is already entered in the list");
return;
}
}
persons.add(person);
}
這將在找到匹配項時退出該方法,如果沒有匹配項,person則在回圈之后簡單地添加。請注意return第一次檢查中的 。
此代碼的優化可能是使用MaporSet來加速包含檢查;也只是使用anyMatch會persons導致更優雅的解決方案。
重復是由您的
for回圈及其else條件引起的。如果BobandJan在您的集合中并且您添加了第二個BobthenJan將不等于Bob并且您的else路徑被執行添加一個副本到您的 finalpersonsList。
uj5u.com熱心網友回復:
您可以使用 Set 而不是 list 這將滿足您的需要并實作比較器或可比較的介面以進行人員比較
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438476.html
下一篇:帶有兩個謂詞的磁區
