gpt4 book ai didi

java - 上限泛型的问题

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

我在处理包含使用泛型的成员的类时遇到了一些问题。考虑以下示例类:

class BaseRequest {
// Content goes here
}

class SubRequest extends BaseRequest {
// IFace methods go here, etc.
}

// Simple datastructure interface
interface Structure<T> {

List<T> getElementsList();


Collection<T> getDependencies(T t);
}

// Simple structure implementation, details unimportant
class StructureImpl<T> implements Structure<T> {

@Override
public List<T> getElementsList() {
// Implementation details not important
return null;
}


@Override
public Collection<T> getDependencies(T t) {
// implementation details not important
return null;
}
}

然后我有以下使用结构的类

class StructureUsingObject {
final Structure<BaseRequest> structure;


public StructureUsingObject(Structure<BaseRequest> structure) {
this.structure = structure;
}


public void foo() {
for (BaseRequest request : structure.getElementsList()) {
Collection<BaseRequest> requests = this.structure.getDependencies(request);
// do things
}
}
}

这本身是行不通的;

public void foo() {
StructureImpl<BaseRequest> baseImpl = new StructureImpl<BaseRequest>();
StructureUsingObject baseStruct = new StructureUsingObject(baseImpl);

StructureImpl<SubRequest> subImpl = new StructureImpl<SubRequest>();
// Compile error on this line
StructureUsingObject subStruct = new StructureUsingObject(subImpl);
}

这是有道理的; StructureImpl 实际上并不是 StructureImpl 的子类。因此,我尝试修改 StructureUsingObject 以使用通配符:

    class StructureUsingObject {
final Structure<? extends BaseRequest> structure;


public StructureUsingObject(Structure<? extends BaseRequest> structure) {
this.structure = structure;
}


public void foo() {
for (BaseRequest request : structure.getElementsList()) {
// Compile error on this line
Collection<BaseRequest> requests = this.structure.getDependencies(request);

// To clarify, a compile error would happen here as well; the issue isn't with the return type
this.structure.getDependencies(request);

// do things
}
}
}

这也不起作用;

The method getDependencies(capture#4-of ? extends BaseRequest) in the type Structure<capture#4-of ? extends BaseRequest> is not applicable for the arguments (BaseRequest)

好吧,这也是有道理的,尽管自动完成工具提示没有(它指出 getDependency 应该将 (null t) 作为其参数)。我不太确定从这里该去哪里。我无法在 foreach 中使用通配符。如何满足我的 StructureUsingObject 可以接受具有 BaseRequest 子类的结构的要求,同时还能够使用列表中的元素调用 getDependency?

最佳答案

调整您的最新版本以捕获通配符。

public void foo() {
bar(this.structure);
}

private <T extends BaseRequest> void bar(Structure<T> s) {
for (T request : s.getElementsList()) {
Collection<T> requests = s.getDependencies(request);

// do things
}
}

关于java - 上限泛型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15974370/

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