gpt4 book ai didi

java - 如何正确使用泛型类型的数组?

转载 作者:IT老高 更新时间:2023-10-28 20:57:58 24 4
gpt4 key购买 nike

我有一个类,它根据消息的类将传入消息映射到匹配的阅读器。所有消息类型都实现接口(interface)消息。读取器在映射器类中注册,说明它将能够处理哪些消息类型。这些信息需要以某种方式存储在消息阅读器中,我的方法是从构造函数中设置一个 private final 数组。

现在,我似乎对泛型和/或数组有一些误解,我似乎无法弄清楚,请参阅下面的代码。这是什么?

public class HttpGetMessageReader implements IMessageReader {
// gives a warning because the type parameter is missing
// also, I actually want to be more restrictive than that
//
// private final Class[] _rgAccepted;

// works here, but see below
private final Class<? extends IMessage>[] _rgAccepted;

public HttpGetMessageReader()
{
// works here, but see above
// this._rgAccepted = new Class[1];

// gives the error "Can't create a generic array of Class<? extends IMessage>"
this._rgAccepted = new Class<? extends IMessage>[1];

this._rgAccepted[0] = HttpGetMessage.class;
}
}

预计到达时间:正如 cletus 正确指出的那样,最基本的谷歌搜索表明 Java 不允许泛型数组。对于给出的示例,我绝对理解这一点(例如 E[] arr = new E[8],其中 E 是周围类的类型参数)。但是为什么允许 new Class[n] 呢?那么什么是“正确的”(或至少是常见的)方法来做到这一点?

最佳答案

Java 不允许 generic arrays .更多信息请访问 Java Generics FAQ .

要回答您的问题,只需使用 List (可能是 ArrayList )而不是数组。

更多解释见 Java theory and practice: Generics gotchas :

Generics are not covariant

While you might find it helpful to think of collections as being an abstraction of arrays, they have some special properties that collections do not. Arrays in the Java language are covariant -- which means that if Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a Number[], and you are free to pass or assign an Integer[] where a Number[] is called for. (More formally, if Number is a supertype of Integer, then Number[] is a supertype of Integer[].) You might think the same is true of generic types as well -- that List<Number> is a supertype of List<Integer>, and that you can pass a List<Integer> where a List<Number> is expected. Unfortunately, it doesn't work that way.

It turns out there's a good reason it doesn't work that way: It would break the type safety generics were supposed to provide. Imagine you could assign a List<Integer> to a List<Number>. Then the following code would allow you to put something that wasn't an Integer into a List<Integer>:

List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));

Because ln is a List<Number>, adding a Float to it seems perfectly legal. But if ln were aliased with li, then it would break the type-safety promise implicit in the definition of li -- that it is a list of integers, which is why generic types cannot be covariant.

关于java - 如何正确使用泛型类型的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/897251/

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