Last active
February 1, 2022 12:30
-
-
Save Miha-x64/d2b2156f67e5c27b9061969d2d44b756 to your computer and use it in GitHub Desktop.
Utility-class for marking several ArrayList elements as removed and removing them all then.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.aquadc.util; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.List; | |
/** | |
* For lists with O(n) random-deletion time (array-based lists, like {@link ArrayList}), | |
* it's faster to mark items as removed and them sweep them all together. | |
* | |
* In general, this is a bit slower than removing from LinkedList, | |
* but memory footprint, adding to end and reading performance is better. | |
* | |
* After {@link #markAsRemoved} call(s), list is in inconsistent state (heap pollution), | |
* so no one should read it before {@link #commitRemovals} called. | |
* | |
* This mechanism is borrowed from {@link android.util.SparseArray}. | |
* <a href="https://gist.github.com/Miha-x64/d2b2156f67e5c27b9061969d2d44b756">This Gist location</a> | |
*/ | |
@SuppressWarnings({"unchecked", "SuspiciousMethodCalls", "rawtypes"}) | |
public final class ArrayLists { | |
private ArrayLists() {} | |
private static final Object REMOVED = new Object(); | |
private static final Collection<Object> COLLECTION_OF_REMOVED = Collections.singleton(REMOVED); | |
/** | |
* Marks element at {@param idx} as removed. | |
* Don't show this list to anyone until you call {@link #commitRemovals}! | |
*/ | |
public static void markAsRemoved(ArrayList<?> list, int idx) { | |
((List) list).set(idx, REMOVED); | |
} | |
/** | |
* Actually removes all items which were marked as removed by {@link #markAsRemoved}. | |
*/ | |
public static boolean commitRemovals(ArrayList<?> list) { | |
return list.removeAll(COLLECTION_OF_REMOVED); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment