4

I have a question. When working with Dart, I can't check to see if 2 arrays are equal. (in other languages, I can do with ==) In fact, I just can do that == with String or number.

List arr1 = [1,2,3];
List arr2 = [1,2,3];

if (arr1 == arr2) {
  print("equal");
} else {
  print("not equal");
}

// Output: not equal.

So I wonder how does that make sense. I mean, How we can do if the == is just work for the cases of String or number (if the values compared are the same). How do I have to do if I want to check that kind of comparison (equal) for List, Map, .. It just work for String & number.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
user3071121
  • 605
  • 2
  • 8
  • 12

1 Answers1

6

arr1 and arr2 are different instances of an object of type List. By default different instances are always different.
When a class implements a custom == operator it can override this behavior. Some classes have a custom implementation by default like int and String.
This can easily be done for immutable objects but not for mutable. One reason is that usually the hashCode is calculated from the values stroed in a class and the hashCode must not change for an instance because this can for example cause that an instance stored in a map can't be retrieved anymore when the hashcode of the key changed.

As a workaround there is a library that provides helper functions to compare lists/iterables.

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");
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567