How to implement ConcurrentHashSet in .Net

I just ran into a similar scenario (“I am interested in a fast Add and Contains and Remove”) and implemented this sucker: using System.Collections.Generic; using System.Threading; namespace BlahBlah.Utilities { public class ConcurrentHashSet<T> : IDisposable { private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); private readonly HashSet<T> _hashSet = new HashSet<T>(); #region Implementation of ICollection<T> …ish public … Read more

How to use Comparer for a HashSet

A HashSet doesn’t need a IComparer<T> – it needs an IEqualityComparer<T>, such as public class SynonymComparer : IEqualityComparer<Synonym> { public bool Equals(Synonym one, Synonym two) { // Adjust according to requirements. return StringComparer.InvariantCultureIgnoreCase .Equals(one.Name, two.Name); } public int GetHashCode(Synonym item) { return StringComparer.InvariantCultureIgnoreCase .GetHashCode(item.Name); } } However, your current code only compiles because you’re creating … Read more

Why can’t I retrieve an item from a HashSet without enumeration?

In .Net, what you are probably looking for is KeyedCollection http://msdn.microsoft.com/en-us/library/ms132438.aspx You can get around the nastiness of re-implementing this abstract class each time with some “generic” cleverness. (See IKeyedObject`1.) Note: Any data transfer object which implements IKeyedObject`1 should have an overridden GetHashCode method simply returning this.Key.GetHashCode(); and same goes for equals… My Base Class … Read more

How can I convert a Java HashSet to a primitive int array?

You can create an int[] from any Collection<Integer> (including a HashSet<Integer>) using Java 8 streams: int[] array = coll.stream().mapToInt(Number::intValue).toArray(); The library is still iterating over the collection (or other stream source) on your behalf, of course. In addition to being concise and having no external library dependencies, streams also let you go parallel if you … Read more

HashSet contains duplicate entries

The problem is that your Element class has not overridden the equals and hashCode methods or these implementations are broken. From Object#equals method javadoc: The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference … Read more