Dart提供了mapEquals
方法用于比较两个Map是否深度相等,示例代码:
import 'package:flutter/foundation.dart';
void main() {
Map map1 = {'size': 38, 'color': 'red'};
Map map2 = {'size': 38, 'color': 'red'};
if(mapEquals(map1, map2)){
print('yes');
}else{
print('no');
}
}
下面我们来看一下mapEquals
的源代码,一起研究一下方法具体是如何判断深度相等的:
/// Compares two maps for deep equality.
///
/// Returns true if the maps are both null, or if they are both non-null, have
/// the same length, and contain the same keys associated with the same values.
/// Returns false otherwise.
///
/// The term "deep" above refers to the first level of equality: if the elements
/// are maps, lists, sets, or other collections/composite objects, then the
/// values of those elements are not compared element by element unless their
/// equality operators ([Object.==]) do so.
///
/// See also:
///
/// * [setEquals], which does something similar for sets.
/// * [listEquals], which does something similar for lists.
bool mapEquals<T, U>(Map<T, U>? a, Map<T, U>? b) {
if (a == null)
return b == null;
if (b == null || a.length != b.length)
return false;
/// Check whether two references are to the same object.
if (identical(a, b))
return true;
for (final T key in a.keys) {
if (!b.containsKey(key) || b[key] != a[key]) {
return false;
}
}
return true;
}
mapEquals
的源代码相对比较简单,通过三个if
语句和一个for
循环语句可以看出,仅有三种情况会返回True:
- 如果两个map都是
null
的话,返回True; - 两个map对象的引用相同,返回True;
- 两个map的长度相对、key相等及key对应的
value
也同时相等时,返回True。
需要注意的是如果key
对应的value
是maps
, lists
, sets
,或其他集合/复合对象,则这些元素的值不会逐个深入进行比较,而是通过相等运算符==
来比较。
网友评论