Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use lists as keys in a map

Tags:

dart

print({[1,2]:3}[[1,2]]) prints null. This is obviously unexpected.

Is there a blessed workaround or do I have to create a new list-like-class/wrapper and give it a proper operator== and hashCode?

like image 225
user Avatar asked Sep 22 '14 08:09

user


2 Answers

Lists in Dart do not have equality based on their elements.

You can use a Map with a custom equality function. There is an equality on lists defined in package:collection/equality.dart, so you can do:

import "dart:collection";
import "package:collection/equality.dart";
main() {
  const eq = const ListEquality();
  var map = HashMap(equals: eq.equals, hashCode: eq.hash, isValidKey: eq.isValidKey);
  map[[1,2]] = 42;
  print(map[[1,2]]);
}

That still won't allow you to use a map literal, though.

like image 64
lrn Avatar answered Nov 12 '22 18:11

lrn


There is an open issue for this: http://dartbug.com/17963 and maybe http://dartbug.com/2217

Hashmap has a constructor that accepts functions to calculate equality and the hashCode:

HashMap({
    Function bool equals(K key1, K key2), 
    Function int hashCode(K key), 
    Function bool isValidKey(potentialKey)})

You should be aware that when you calculate the hashCode dependent on the elements contained in the list and you modify the list while it is contained in the map you won't find it anymore (like in your example)

like image 31
Günter Zöchbauer Avatar answered Nov 12 '22 17:11

Günter Zöchbauer