我很難從自定義對象的ArrayList中刪除重複的項目。從ArrayList刪除重複的自定義對象
刪除重複
public static ArrayList<UnchainedRestaurant> removeDuplicates(ArrayList<UnchainedRestaurant> arraylist) {
//remove any duplicates
ArrayList<UnchainedRestaurant> noDuplicates = new ArrayList<>();
Set<UnchainedRestaurant> setItems = new LinkedHashSet<UnchainedRestaurant>(arraylist);
noDuplicates.addAll(setItems);
return noDuplicates;
}
自定義對象的equals()
public boolean equals(Object o) {
UnchainedRestaurant r = (UnchainedRestaurant) o;
String name1 = this.getName();
String name2 = r.getName();
name1 = Util.normalizeVenueName(name1);
name2 = Util.normalizeVenueName(name2);
if(name1.equals(name2)) {
return true;
} else return false;
}
輸出刪除重複後
1. 786 Kebab & Curry
2. Marlow's Tavern
3. P.F. Chang's
4. Ted's Montana Grill
5. Which Wich? Superior Sandwiches
6. Niko Niko Sushi
7. Burger 21
8. Tin Lizzys Bar and Grille
9. Saigon Flavors
10. Firehouse Subs
11. Luigi's Pizza
12. Roya Mediterranean Restaurant and Tapas Bar
13. East Coast Wings & Grill
14. Provino's Italian Restaurant
15. Kani House
16. Chow Baby
17. Mimi's Cafe
18. Monterrey Mexican Restaurant
19. Panera Bread - Mall of Georgia
20. Umami Asian Cuisine
21. Parma Tavern
7. Burger 21 --------------------------------
23. Luigi's A Slice of Italy
4. Ted's Montana Grill --------------------------------
25. Tom + Chee - Buford
2. Marlow's Tavern --------------------------------
1. 786 Kebab & Curry
28. Sushi Niko Niko
13. East Coast Wings & Grill
3. P.F. Chang's --------------------------------
31. Turkish Kitchen
32. The Cheesecake Factory
17. Mimi's Cafe
34. Aha Sushi
15. Kani House
3. P.F. Chang's --------------------------------
37. Teavana
38. Williams-Sonoma
39. Great Wraps
40. Auntie Anne's Pretzels
1. 786 Kebab & Curry --------------------------------
42. Bruster's Real Ice Cream
43. Spencer Gifts
44. Pretzelmaker
45. Little Tokyo of Georgia Mall
46. Great American Cookies
關於爲什麼它實際上並沒有刪除重複的任何提示?或者它是否通過用原始文件替換重複文件來刪除重複文件?不知道這裏發生了什麼。
如果重寫equals,你需要重寫哈希碼爲好。 –
如果你做了什麼@AlexisC。說你可以把它改成一個[Set](http://docs.oracle.com/javase/7/docs/api/java/util/Set.html),它會爲你做! – StackFlowed
@StackFlowed OP已經使用了一個'LinkedHashSet'。 – RealSkeptic