.NET port with Java map, Set, HashMap

I am porting Java code to .NET, and I am stuck in the following lines which (behave unexpectedly in .NET).

Java

Map<Set<State>, Set<State>> sets = new HashMap<Set<State>, Set<State>>(); Set<State> p = new HashSet<State>(); if (!sets.containsKey(p)) { ... } 

Equivalent .NET code can be:

 IDictionary<HashSet<State>, HashSet<State>> sets = new Dictionary<HashSet<State>, HashSet<State>>(); HashSet<State> p = new HashSet<State>(); if (!sets.containsKey(p)) { /* (Add to a list). Always get here in .NET (??) */ } 

However, the code comparison is not performed, the program believes that the β€œinstall” never contains the key β€œp” and ultimately leads to an OutOfMemoryException.

Perhaps I missed something, the equivalence and identity of objects may be different between Java and .NET.

I tried to implement IComparable and IEquatable in the State class, but the results were the same.

Edit:

What the code does: if there is no p key in the sets (which is a HashSet), it will add a p to the end of LinkedList>.

The State class (Java) is a simple class defined as:

 public class State implements Comparable<State> { boolean accept; Set<Transition> transitions; int number; int id; // ... public int compareTo(State s) { return s.id - id; } public boolean equals(Object obj) { return super.equals(obj); } public int hashCode() { return super.hashCode(); } 
+4
source share
1 answer

In Java, the list and installed implementations override equals , etc. Equivalent not found in .NET. However, you can create the dictionary using the appropriate comparison HashSet<T>.CreateSetComparer using the HashSet<T>.CreateSetComparer and pass it to the Dictionary constructor as follows:

 IDictionary<HashSet<State>, HashSet<State>> sets = new Dictionary<HashSet<State>, HashSet<State>> (HashSet<State>.CreateSetComparer()); 

State is supposed to override Equals/GetHashCode and implements IEquatable<State> ideally too.

+4
source

Source: https://habr.com/ru/post/1380890/


All Articles