gpt4 book ai didi

java - 使用匿名内部类遍历二叉搜索树

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:27 26 4
gpt4 key购买 nike

更新:如何在不修改界面的情况下最好地添加持续时间?

我无法访问匿名内部类实例的方法。我收到 sum.totalTime() 调用的编译时错误 - “Traverser 类型的方法 TotalTime() 未定义”

我有一个 Traverser 界面。

interface Traverser<E> {
public void visit(E x);
}

我想使用该接口(interface)来添加 SongEntry 对象的持续时间属性。因此,我实例化了一个匿名内部类,并为每次访问()调用增加了一个 TotalTime 属性,以及该属性的 getter。

在另一个类(class)中,我有以下代码:

Traverser<SongEntry> sum = new Traverser<SongEntry>() {
private int totalTime;

public void visit(SongEntry song) {
totalTime += song.getDuration();
}

public int totalTime() {
return totalTime;
}
};

myPlayList.traverse(sum);

int total = sum.totalTime(); // causes compile-time error "the method totalTime() is undefined for the type Traverser<SongEntry>"

myPlayList 是一个二分搜索 ADT,它在每个元素上运行传递仿函数的 Visit() 方法。

最佳答案

由于 sum 的类型为 Traverser,因此您只能调用在 Traverser 接口(interface)中声明的方法。您的选择是:

  • 只需将函数 public int TotalTime(); 添加到界面即可定义。
  • 使用所需的函数声明创建第二个接口(interface)扩展Traverser
  • 创建一个非匿名内部类并实现穿越者

关于java - 使用匿名内部类遍历二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533398/

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