gpt4 book ai didi

java - 扩展方法中的返回类型哈希表

转载 作者:行者123 更新时间:2023-12-01 15:42:15 25 4
gpt4 key购买 nike

我有一个接口(interface) Node 要求方法:

public HashSet getNeighbour();

NodeVariable 实现 Node,它的邻居是 NodeFunction 类型(也实现 Node),我编写了该方法:

public HashSet<NodeFunction> getNeighbour();

(在 NodeFunction 类中反之亦然)。

我发现如果我将 Node 中方法的签名更改为:

public HashSet<Node> getNeighbour();

然后在 NodeVariable 和 NodeFunction 中的方法上我收到错误:

Error getNeighbour() in factorgraph.NodeFunction cannot implement getNeighbour() in factorgraph.Node return type java.util.HashSet is not compatible with java.util.HashSet NodeFunction.java

这个还不太清楚。

我发现:

Overriding return type in extended interface - Bad idea?

Java - Overriding return type of extended interface when return type uses generics for own method parameter types

现在我更改了 Node 方法签名:

public HashSet<? extends Node> getNeighbour();

因此编译器不再提示。

是吗?为什么 HashSet 不被视为 HashSet 的“扩展”?

最佳答案

首先,最好根据其他接口(interface)而不是具体实现来定义接口(interface)中的方法。我想说的是 getNeighbour() 方法应该是:

public Set getNeighbour();

既然我们知道它只能返回 Node(或 Node 的子类型),我们不妨这样定义它:

public Set<? extends Node> getNeighbour();

关于java - 扩展方法中的返回类型哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7867152/

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