gpt4 book ai didi

Java通用上限通配符错误

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

我的领域模型中有以下实体:

class Point {
public String details;

public Point() {
details = "empty";
}

public Point(String details) {
this.details = details;
}
}

class BasicPoint<X, Y> extends Point {
public X x;
public Y y;

public BasicPoint() {}

public BasicPoint(X x, Y y) {
this.x = x;
this.y = y;
}
}

class Collector<T> {
T elem;

public void collect(T elem) {
this.elem = elem;
}
}

我想对数据应用操作并将该数据作为 Point 或 BasicPoint 返回,如上声明,但编译器提示以下错误,尽管 OUT 扩展了 Point:

class Operator<OUT extends Point> {
public Collector<OUT> operate(Collector<OUT> collector) {

// compile error, collect(OUT) cannot be applied to BasicPoint<Integer, Integer>
collector.collect(new BasicPoint<Integer, Integer>(1,2));

return collector;
}
}

主要方法应该如下所示:

Collector<BasicPoint<Integer, Integer>> c = new Collector<>();
c = new Operator<BasicPoint<Integer, Integer>>().operate(c);
System.out.println(c.elem.getClass() == new BasicPoint<Integer, Integer>().getClass());

最佳答案

您的 Operator 是通用的,它不能在 BasicPoint 上应用 collect,只能 OUT。您可以使您的 Collector 抽象:

abstract class Operator<OUT extends Point> {
abstract Collector <OUT> operate(Collector<OUT> collector);
}

然后 BasicPointOperator 将包含您想要的实际实现:

class BasicPointOperator extends Operator<BasicPoint<Integer, Integer>> {

@Override
Collector<BasicPoint<Integer, Integer>> operate(Collector<BasicPoint<Integer, Integer>> collector) {
collector.collect(new BasicPoint<Integer, Integer>(1,2));
return collector;
}
}

PointOperator,更通用一些

class PointOperator extends Operator<Point> {

@Override
Collector<Point> operate(Collector<Point> collector) {
collector.collect(new BasicPoint<Integer, Integer>(1,2));
return collector;
}
}

关于Java通用上限通配符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37206564/

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