我如何正确使用泛型类型的数组

我如何正确使用泛型类型的数组

本文介绍了我如何正确使用泛型类型的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  public class HttpGetMessageReader实现IMessageReader {
//因为缺少类型参数而给出警告
//另外,我实际上想要比
//
// private final Class [] _rgAccepted;

//在这里工作,但在下面看到
private final Class< ;?扩展IMessage> [] _rgAccepted;

public HttpGetMessageReader()
{
//在这里工作,但在上面看到
// this._rgAccepted = new Class [1];

//给出错误无法创建Class的通用数组< ;? extends IMessage>
this._rgAccepted = new Class
this._rgAccepted [0] = HttpGetMessage.class;
}
}

ETA
正如Cletus正确指出的那样,最基本的Google搜索表明Java不允许泛型数组。我明确地理解了这个例子(例如 E [] arr = new E [8] ,其中 E 是周围类的类型参数)。但为什么新的Class [n] 允许?那么,什么是正确的(或至少是普通的)方式来做到这一点? 解决方案

不允许。更多信息请参阅。



要回答您的问题,只需使用(可能是:
$ b


I have a class that maps incoming messages to matching readers based on the message's class. All message types implement the interface message. A reader registers at the mapper class, stating which message types it will be able to handle. This information needs to be stored in the message reader in some way and my approach was to set a private final array from the constructor.

Now, it seems I have some misunderstanding about generics and / or arrays, that I can't seem to figure out, see the code below. What is it?

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;
    }
}

ETA:As cletus correctly pointed out, the most basic googling shows that Java does not permit generic arrays. I definitely understand this for the examples given (like E[] arr = new E[8], where E is a type parameter of the surrounding class). But why is new Class[n] allowed? And what then is the "proper" (or at least, common) way to do this?

解决方案

Java does not permit generic arrays. More information in the Java Generics FAQ.

To answer your question, just use a List (probably ArrayList) instead of an array.

Some more explanation can be found in Java theory and practice: Generics gotchas:

这篇关于我如何正确使用泛型类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:36