gpt4 book ai didi

dart - 为什么Set不包含Point

转载 作者:行者123 更新时间:2023-12-03 02:53:13 24 4
gpt4 key购买 nike

我有一个Set<Point<double>>,我想测试该集合是否包含特定的Point<double>

我的理解是,如果两个Point<double>实例具有相同的hashCode并根据==相等,则默认Set实现会认为它们相同,并且当其中一个点位于集合中时将返回true,我们将使用contains测试其他点。

但是在以下示例中,情况似乎并非如此:

import 'dart:math';

void main() {
final points = Set<Point<double>>.identity();
final a = Point<double>(5, 2);
final b = Point<double>(5, 2);

points.add(a);

print("a == b ? ${a == b}");
print("a.hashCode == b.hashCode ? ${a.hashCode == b.hashCode}");
print("points.contains(a) ? ${points.contains(a)}");
print("points.contains(b) ? ${points.contains(b)}");
}

According to DartPad的输出是:
a == b ? true
a.hashCode == b.hashCode ? true
points.contains(a) ? true
points.contains(b) ? false

我在哪里错了?

最佳答案

发生这种情况是因为thay不相同,但是您指定了通过身份而不是等效性来比较它们。

import 'dart:math';

void main() {
//final points = Set<Point<double>>.identity();
final points = Set<Point<double>>();
final a = Point<double>(5, 2);
final b = Point<double>(5, 2);

points.add(a);

print("a == b ? ${a == b}");
print("a.hashCode == b.hashCode ? ${a.hashCode == b.hashCode}");
print("points.contains(a) ? ${points.contains(a)}");
print("points.contains(b) ? ${points.contains(b)}");
}

您禁用了此运算符。
 /**
* A `Point` is only equal to another `Point` with the same coordinates.
*
* This point is equal to `other` if, and only if,
* `other` is a `Point` with
* [x] equal to `other.x` and [y] equal to `other.y`.
*/
bool operator ==(dynamic other) =>
// Cannot change parameter type to `Object` in case some class
// inherits the type and uses their argument dynamically.
other is Point && x == other.x && y == other.y;

对此进行了详细说明(使用等于:相同)。
/**
* Creates an insertion-ordered identity-based set.
*
* Effectively a shorthand for:
*
* new LinkedHashSet<E>(equals: identical,
* hashCode: identityHashCode)
*/
external factory LinkedHashSet.identity();

关于dart - 为什么Set不包含Point,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54982512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com