Remove Elements from a HashSet while Iterating [duplicate]

You can manually iterate over the elements of the set: Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()) { Integer element = iterator.next(); if (element % 2 == 0) { iterator.remove(); } } You will often see this pattern using a for loop rather than a while loop: for (Iterator<Integer> i = set.iterator(); i.hasNext();) { Integer element … Read more

Collection that allows only unique items in .NET?

HashSet<T> is what you’re looking for. From MSDN (emphasis added): The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. Note that the HashSet<T>.Add(T item) method returns a bool — true if the item was added to the collection; false … Read more

How to sort a HashSet?

A HashSet does not guarantee any order of its elements. If you need this guarantee, consider using a TreeSet to hold your elements. However if you just need your elements sorted for this one occurrence, then just temporarily create a List and sort that: Set<?> yourHashSet = new HashSet<>(); … List<?> sortedList = new ArrayList<>(yourHashSet); … Read more

How does HashSet compare elements for equality?

It uses an IEqualityComparer<T> (EqualityComparer<T>.Default unless you specify a different one on construction). When you add an element to the set, it will find the hash code using IEqualityComparer<T>.GetHashCode, and store both the hash code and the element (after checking whether the element is already in the set, of course). To look an element up, … Read more

HashSet vs LinkedHashSet

The difference between the two are, as you’ve stated: A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through … Read more

Why is HashSet so much slower than HashSet?

There are two perf problems induced by the Point struct. Something you can see when you add Console.WriteLine(GC.CollectionCount(0)); to the test code. You’ll see that the Point test requires ~3720 collections but the string test only needs ~18 collections. Not for free. When you see a value type induce so many collections then you need … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)