Java自定义retainAll方法逻辑错误排查求助
Hey there, let's take a look at your retainAll implementation—there are a few key issues that are causing it to not behave as expected. Let's break them down one by one:
- You're iterating the wrong collection: Your code uses an iterator for the input collection
c, butretainAllis supposed to modify the current collection (this) by keeping only elements that exist inc. Iterating overcdoesn't help you check which elements in your own list need to be removed. - The containment check is redundant (and backwards for your goal): Since
itris an iterator forc, every element you get fromitr.next()is definitely present inc. That means!c.contains(itr.next())will never be true, so your code never actually removes any elements from your list. - Returning too early: Even if you had the right logic, returning
trueimmediately after removing one element would stop processing the rest of the elements, leaving unwanted items in your list. The method should only returntrueif any elements were removed (after processing all elements), not just the first one.
Here's the corrected implementation that matches your expected behavior:
@Override public boolean retainAll(Collection<?> c) { if (c == null) { throw new NullPointerException("collection is null"); } boolean modified = false; Iterator<?> itr = this.iterator(); // Iterate over the current list (listA) while (itr.hasNext()) { Object element = itr.next(); if (!c.contains(element)) { // Remove elements NOT present in the input collection (listB) itr.remove(); modified = true; // Track that we've made changes to the list } } return modified; // Return true only if any elements were removed }
Let's walk through why this works for your scenario:
- We iterate over
this(yourlistA) instead oflistB, so we can check every element in the list we want to modify. - For each element in
listA, we check if it isn't present inlistB—if that's true, we remove it fromlistA. - We use a
modifiedflag to track if any changes were made. This aligns with theretainAllcontract: returntrueif the collection was altered during the operation.
If you run this with your test case—listA containing "Hey", "1", "2", "3", "4", "Bro" and listB containing "Hey", "Bro"—listA will correctly retain only "Hey" and "Bro".
内容的提问来源于stack exchange,提问作者CenturiDamos
相关产品推荐
相关产品推荐

