Sunday, 15 May 2011

2 same content arrays are not equal in Dart? -



2 same content arrays are not equal in Dart? -

i have question. when working dart, can't check see if 2 arrays equal. (in other languages, can ==) in fact, can == string or number.

class="lang-dart prettyprint-override">list arr1 = [1,2,3]; list arr2 = [1,2,3]; if (arr1 == arr2) { print("equal"); } else { print("not equal"); }

// output: not equal.

so wonder how create sense. mean, how can if == work cases of string or number (if values compared same). how have if want check kind of comparing (equal) list, map, .. work string & number.

arr1 , arr2 different instances of object of type list. default different instances different. when class implements custom == operator can override behavior. classes have custom implementation default int , string. can done immutable objects not mutable. 1 reason hashcode calculated values stroed in class , hashcode must not alter instance because can illustration cause instance stored in map can't retrieved anymore when hashcode of key changed.

as workaround there library provides helper functions compare lists/iterables.

class="lang-dart prettyprint-override">import 'package:collection/equality.dart'; void main(list<string> args) { if (const iterableequality().equals([1,2,3],[1,2,3])) { // if (const setequality().equals([1,2,3].toset(),[1,2,3].toset())) { print("equal"); } else { print("not equal"); } }

dart

No comments:

Post a Comment