0

Upd: I see that my question is duplicate and my problem is: this is not safe to use generics in arrays. But how do I need to change my code to fix this? All I came up is (and I even doesn't know if this code is similar to old)

_readWriteThreads = (ReadWriteThread<T, RP, SP>[]) Array.newInstance(ReadWriteThread.class, sc.getSelectorThreadCount());

But this code also gave me a warning.


Previous post (Raw types warning):

I'm not a java developer, but I want to fix the only warning in my project in this part of code:

public abstract class SelectorThread<T extends MMOConnection<T, RP, SP>, RP extends ReceivablePacket<T, RP, SP>, SP extends SendablePacket<T, RP, SP>>
{
    protected static final Log _log = new MMOLogger(SelectorThread.class, 1000);

    private final AcceptorThread<T, RP, SP> _acceptorThread;
    private final ReadWriteThread<T, RP, SP>[] _readWriteThreads;


    protected SelectorThread(SelectorConfig sc, IPacketHandler<T, RP, SP> packetHandler) throws IOException
    {
        _acceptorThread = new AcceptorThread<T, RP, SP>("AcceptorThread", this, sc);
        _readWriteThreads = new ReadWriteThread[sc.getSelectorThreadCount()];

        for (int i = 0; i < _readWriteThreads.length; i++)
            _readWriteThreads[i] = new ReadWriteThread<T, RP, SP>("ReadWriteThread-" + (i + 1), this, sc, packetHandler);
    }

    ...
}

The warning:

Type safety: The expression of type ReadWriteThread[] needs unchecked
conversion to conform to ReadWriteThread<T,RP,SP>[]

Please, can someone help me fix this, or tell me what I must know to fix this. I understand that line above is fixed by <T, RP, SP>, but this doesn't work with array.

Community
  • 1
  • 1

1 Answers1

0

Arrays and generics don't play well together. You can make them work, just about, but it's a lot of effort.

A much better solution is to use a List, probably an ArrayList, for which generics "just work":

private final List<ReadWriteThread<T, RP, SP>> _readWriteThreads;

initialize it using

_readWriteThreads = new ArrayList<>();

then

_readWriteThreads.add(
    new ReadWriteThread<T, RP, SP>("ReadWriteThread-" + (i + 1), this, sc, packetHandler));
Andy Turner
  • 137,514
  • 11
  • 162
  • 243