Why is value comparison in hashtable returning false even when the values are the same?

后端 未结 2 522
花落未央
花落未央 2021-01-21 03:12

In the following code, I am trying to check if two strings are anagrams. To that, I am counting the characters in the two strings in a hash table by storing the unique character

2条回答
  •  半阙折子戏
    2021-01-21 03:34

    Your problem comes from the fact that != will compare reference equality on two objects. uniqueCharsX[key] returns a int boxed inside a object, while you have the same int being returned from both hashtables the box they are being returned in is not the same box so you get a incorrect value.

    Either use a strongly typed Dictionary instead of a hashtable or use !uniqueChars1[key].Equals(uniqueChars2[key]) instead of uniqueChars1[key] != uniqueChars2[key] which will unbox the int and compare on the value instead (I highly recommend you use the Dictionary.)

提交回复
热议问题