Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a .NET Hashtable work just like a Java Hashtable

When I add some items into a Java Hashtable, their order is different to that of a .NET Hashtable. Is there any way I can make sure the .NET Hashtable will have the same order as a Java Hashtable?


I'm trying to port some Java code to C#. The Java code uses a Hashtable to keep track of some data. When I check to see the order the data is retrieved when I iterate through either the Java Hashtable or the .NET Hashtable (via an Enumerator), each one consistently has the same data, in the same order ... but each code based has a different order.

Is there any way I can make it so that the .NET Hashtable data is in the same order as the Java Hashtable?

I understand that Hashtable do not handling ordering - so I feel like there's nothing that can be done. I also cannot change the datatype in the Java code from .. say .. a Hashtable to something else.

Here's some same data to illustrate my situation.

Data, added sequential for either code base :-

  1. num | someData
  2. pagenum | someData
  3. x | someData
  4. top | someData

Java Code:

private Hashtable identifiers = new Hashtable();
...
identifiers.put(symbol, identifier);

Java output via iteration over an enumerator:

alt text

.NET code:

private Hashtable Identifiers = new Hashtable();
...
Identifiers.Add(symbol, identifier);

.NET output via iteration over an enumerator.

alt text

Any ideas or suggestions?

like image 329
Pure.Krome Avatar asked Apr 11 '26 02:04

Pure.Krome


2 Answers

Unfortunately, short of changing the type of the collection there's really no way around this. Hashtables don't guarantee order (as you mentioned in your post).

It all boils down to the following:

If order matters, a Hashtable is the wrong data structure.

like image 70
Justin Niessner Avatar answered Apr 12 '26 15:04

Justin Niessner


You cannot change this order short of extracting the keys and sorting them in some way (or using an ordered dictionary). The iteration orders of either of the hashtable implementations you are using are not specified, and therefore relying on a specific order means your code is broken. The iteration order in Java is not even guaranteed to remain the same in future versions of the JDK.

like image 39
cdhowie Avatar answered Apr 12 '26 16:04

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!