为何循环无法获取最后几项?ArrayList去重后丢失末尾元素求助
Hey there! Let's figure out why your last two items are going missing after deduplication. This is a super common pitfall when working with ArrayLists and removing elements, so let's break it down step by step.
First things first: Have you properly overridden the equals() and hashCode() methods in your Item class? The default Object.equals() only compares object references—meaning even if two Item objects have identical identifier, price, and name values, Java will treat them as different if they're separate instances. Without overriding these methods, your deduplication logic won't work at its core.
Next, the most likely culprit behind your missing items: index shifting when removing elements during iteration. Chances are you wrote code like this:
for (int i = 0; i < tempList.size(); i++) { Item item = tempList.get(i); for (int j = i + 1; j < tempList.size(); j++) { if (/* duplicate check logic */) { tempList.remove(j); } } }
When you remove an element at position j, all elements after it shift left by one. But since j still increments in the for loop, you skip over the element that just moved into the j position. This offset causes late elements in the list to be unprocessed, leading them to go missing.
Here are two reliable solutions to fix this:
Solution 1: Use a Map to Count Items (Most Recommended)
This method avoids manual index handling entirely. Use a Map's unique key property to deduplicate automatically, while tracking the count of each item:
First, update your Item class with proper equals() and hashCode():
import java.util.Objects; public class Item { private int identifier; private int price; private String name; // Constructor, getters, setters public Item(int identifier, int price, String name) { this.identifier = identifier; this.price = price; this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; // Adjust this logic based on your definition of a "duplicate" // e.g., if identifier is unique, you only need to compare that return identifier == item.identifier && price == item.price && Objects.equals(name, item.name); } @Override public int hashCode() { return Objects.hash(identifier, price, name); } // For readable output @Override public String toString() { return String.format("Item [ID: %d, Name: %s, Price: %d]", identifier, name, price); } }
Then implement your display method:
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class YourInventoryClass { private ArrayList<Item> list; // Constructor to initialize the list, etc. public void showUniqueItemsWithCount() { Map<Item, Integer> itemCountMap = new HashMap<>(); // Count occurrences of each item for (Item item : list) { itemCountMap.put(item, itemCountMap.getOrDefault(item, 0) + 1); } // Print results System.out.println("Unique Items & Counts:"); for (Map.Entry<Item, Integer> entry : itemCountMap.entrySet()) { System.out.println(entry.getKey() + " | Count: " + entry.getValue()); } // If you need a deduplicated ArrayList: ArrayList<Item> uniqueItems = new ArrayList<>(itemCountMap.keySet()); } }
Solution 2: Fix Manual Iteration to Avoid Index Shifting
If you prefer to handle deduplication manually, use a while loop for the inner iteration to prevent skipping elements:
public ArrayList<Item> getUniqueItems() { // Make a copy of the original list to avoid modifying it directly ArrayList<Item> tempList = new ArrayList<>(list); for (int i = 0; i < tempList.size(); i++) { Item currentItem = tempList.get(i); int j = i + 1; // Use while loop to control index movement while (j < tempList.size()) { if (currentItem.equals(tempList.get(j))) { tempList.remove(j); // Don't increment j here—next element shifted to j's position } else { j++; } } } return tempList; }
To recap: Your missing items are almost certainly due to index skipping when removing elements in a for loop. Fixing that, plus ensuring your Item class has proper equality checks, will resolve the issue.
内容的提问来源于stack exchange,提问作者Red Eyez

