vojelo vojelo - 4 years ago 172
Dart Question

String.hashCode same value for different sequences

What could the problem be? I expect different value of s1.hashCode ad s2.hashCode, but they are the same.

dart --version // Dart VM version: 1.21.1 (Fri Jan 13 09:44:01 2017) on "linux_x64"

main() {
String s1 = "x-14-9";
String s2 = "f-107";
print(s1.hashCode); // 939886624
print(s2.hashCode); // 939886624
print("identical - ${identical(s1,s2)}"); // identical - false
print("== - ${s1 == s2}"); // == - false
}


When I try this code in DartPad - everything is going well, values different.

Answer Source

In many real programs, perfect hash functions do not exist.

That means that different objects may potentially collide (i.e. have the same hashCode, in Dart). Most implementations of things like a HashMap fall back on using an equality check on collisions.

You don't have to worry about this when using the standard library:

var map = new Map<String, int>();
map['x-14-9'] = 1;
map['f-107'] = 2;
print(map); // Should print both key-value pairs.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download