gpt4 book ai didi

java - 在 Java 中使用泛型和类型推断的问题

转载 作者:行者123 更新时间:2023-11-30 08:28:31 25 4
gpt4 key购买 nike

这段时间我在做一个需要某种抽象的项目,但我不知道如何解决一些与java泛型和类型推断相关的问题。

这是源代码的简化架构:

public abstract class BaseDataset
{
// Some data
// Some methods
}

public class DerivedDataset1 extends BaseDataset
{
// Some data
// Implementations of some BaseDataset methods
// Some additional methods
}

public class DerivedDataset2 extends BaseDataset
{
// Some data
// Implementations of some BaseDataset methods
// Some additional methods
}

public interface BaseMeasure<T extends BaseDataset>
{
public float evaluate(T dataset);
}

public class DerivedMeasure1 implements BaseMeasure<DerivedDataset1>
{
@Override
public float evaluate(DerivedDataset1 dataset)
{
// evaluate some measure using DerivedDataset1 methods
return the evaluated measure;
}
}

public class DerivedMeasure2 implements BaseMeasure<DerivedDataset2>
{
@Override
public float evaluate(DerivedDataset1 dataset)
{
// evaluate some measure using DerivedDataset2 methods
return the evaluated measure;
}
}

public class SocialNetworkBuilder
{
public <T extends BaseDataset> void build(T dataset, BaseMeasure<T> measure)
{
float weight = measure.evaluate(dataset);

// ...
}
}

我的问题是,如果在我的主课中,我写了这样的东西:

public class Application
{
public static void main(String [] args)
{
BaseDataset dataset = new DerivedDataset1();
BaseMeasure<? extends BaseDataset> measure = new DerivedMeasure1();
SocialNetworkBuilder socialNetworkBuilder = new SocialNetworkBuilder();
socialNetworkBuilder.build(dataset, measure);
}
}

Eclipse 给我错误:“SocialNetworkBuilder 类型的方法 build(T, BaseMeasure) 不适用于参数 (BaseDataset, BaseMeasure)”

我认为问题在于“构建”方法必须确保数据集和度量属于同一类型 T。

如果我这样做:

public class Application
{
public static void main(String [] args)
{
BaseDataset dataset = new DerivedDataset1();
BaseMeasure<? extends BaseDataset> measure = new DerivedMeasure1();
SocialNetworkBuilder socialNetworkBuilder = new SocialNetworkBuilder();
socialNetworkBuilder.build((DerivedDataset1) dataset, (DerivedMeasure1) measure);
}
}

它有效,但我不能用这种方式解决我的问题,因为我在编译时不知道我的“数据集”和“测量”实例的派生类型; “dataset”和“measure”应该根据运行时给定的一些参数实例化。

我需要在运行时实例化我的“measure”和“dataset”变量,并且仍然能够对它们调用“build”方法。

你有什么想法可以解决这个问题吗?

谢谢。

最佳答案

当您按如下方式更改应用程序时,您的应用程序将编译:

public class Application
{
public static void main(String [] args)
{
DerivedDataset1 dataset = new DerivedDataset1();
BaseMeasure<DerivedDataset1> measure = new DerivedMeasure1();
SocialNetworkBuilder socialNetworkBuilder = new SocialNetworkBuilder();
socialNetworkBuilder.build(dataset, measure);
}
}

关于java - 在 Java 中使用泛型和类型推断的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20163246/

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