2

I am trying to do copy from a LinkedBlockingQueue to a dataStuff[] data array using .toArray() but I am getting an Exception

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LdataStuff;
    at Main.main(Main.java:30)

with the following code

public static BlockingQueue<dataStuff> recurseFragments = new LinkedBlockingQueue<dataStuff>();

    public static void main(String args[]) throws IOException
    {
        dataStuff[] data = (dataStuff[]) recurseFragments.toArray();
    }

I understand that its putting the recurseFragments into an object[] before it spits it into the array but why is it that casting does not work and how can I solve this?

JohnM
  • 105
  • 10

3 Answers3

2

Try using the other toArray method

dataStuff[] data = recurseFragments.toArray(new datastuff[0]);
Zim-Zam O'Pootertoot
  • 17,440
  • 4
  • 38
  • 67
1

Try this:

dataStuff[] data = recurseFragments.toArray(new dataStuff[0])

Using this signature of toArray you can get the correct type of return.

Diego D
  • 1,687
  • 3
  • 21
  • 38
1

Because toArray() returns an Object[]

Object[] toArray();

So , you should use toArray(T[] a) instead.

<T> T[] toArray(T[] a);

Use it this way:

recurseFragments.toArray(new datastuff[0]);
NINCOMPOOP
  • 46,742
  • 15
  • 123
  • 158