gpt4 book ai didi

java - 为什么我的 Java 泛型数组类型传输方法不会调用编译?

转载 作者:行者123 更新时间:2023-12-01 16:59:28 27 4
gpt4 key购买 nike

我正在尝试创建一个系统,该系统允许我获取一个数组中的所有项目,并使用工厂对象将它们转换为另一种类型的项目,并用这些新对象填充第二个数组,然后返回那。我想用泛型来完成这一切,这样就可以在单行静态方法调用中完成。但是,我收到一个无法完全解析的错误。这是(我希望)所有相关代码:

问题类别有:

// ...

// "ArrayPP" is my take on ArrayList that has a lot of convenience methods.
// The constructor here uses varargs to initialize the array:
ArrayPP<String> myStrings = new ArrayPP<>("foo", "bar", "baz");
// MyCharSequenceImpl is just a class that implements CharSequence.
ArrayPP<MyCharSequenceImpl> myCSI = new ArrayPP<>();
// The error occurs on the following line:
myCSI = ArrayPP.transfer(myStrings, new CSToMyCSIFactoryDelegate());

// ...

ArrayPP 具有:

public class ArrayPP<T> implements Iterable<T> {
// ...
// Iterable implementations
// ...

public static <From, To> ArrayPP<To> transfer(Iterable<From> origin, FactoryDelegate<From, To> factory)
{
ArrayPP<To> ret = new ArrayPP<>();
for (From f : origin) {
ret.add(factory.makeFromFactory(f));
}
return ret;
}

// ...
}

FactoryDe​​legate 具有:

public interface FactoryDelegate<From, To> extends Factory<To> {
public To makeFromFactory(From basis);
}

工厂有:

public interface Factory<To> {
public To makeFromFactory();
}

CSToMyCSIFactoryDe​​legate 具有:

public class CSToMyCSIFactoryDelegate implements FactoryDelegate<CharSequence, MyCharSequenceImpl> {
@Override
public MyCharSequenceImpl makeFromFactory(CharSequence basis) {
// MyCharSequenceImpl has a constructor that converts any CharSequence
// into a new MyCharSequenceImpl.
return new MyCharSequenceImpl(basis);
}

@Override
public MyCharSequenceImpl makeFromFactory() {
return makeFromFactory("");
}
}

这是我收到的错误:

error: method transfer in class ArrayPP<T> cannot be applied to given types;
myCSI = ArrayPP.transfer(myStrings, new CSToMyCSIFactoryDelegate());
^
required: Iterable<From>,FactoryDelegate<From,To>
found: ArrayPP<String>,TransferTest.CSToMyCSIFactoryDelegate
reason: inferred type does not conform to equality constraint(s)
inferred: CharSequence
equality constraints(s): CharSequence,String
where From,To,T are type-variables:
From extends Object declared in method <From,To>transfer(Iterable<From>,FactoryDelegate<From,To>)
To extends Object declared in method <From,To>transfer(Iterable<From>,FactoryDelegate<From,To>)
T extends Object declared in class ArrayPP

对我来说,这个错误最令人困惑的部分是它说推断类型不符合等式约束,然后推断类型是CharSequence code> 且等式约束为 CharSequence,String...

为什么我会收到此错误,如何修复我的代码?

最佳答案

看来您需要的是

public static <From, To> ArrayPP<To> transfer(
// vvvvvvvvv
Iterable<? extends From> origin,
FactoryDelegate<From, To> factory
)

因为你只关心origin产生From当你迭代它时,并不一定是 Iterable<From> .

另请参阅

关于java - 为什么我的 Java 泛型数组类型传输方法不会调用编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816396/

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