Error: Generic Array Creation

arrays, class, generics, java, object

Solution

You can't create arrays with a generic component type.

Create an array of an explicit type, like `Object[]`, instead. You can then cast this to `PCB[]` if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like `java.util.List<PCB>` instead of an array.

By the way, if `list` is already a `java.util.List`, you should use one of its `toArray()` methods, instead of duplicating them in your code. This doesn't get you around the type-safety problem though.

Problem

I don't understand the error of Generic Array Creation. First I tried the following: ``` public PCB[] getAll() { PCB[] res = new PCB[list.size()]; for (int i = 0; i < res.length; i++) { res[i] = list.get(i); } list.clear(); return res; } ``` Then I tried doing this: ``` PCB[] res = new PCB[100]; ``` I must be missing something cause that seems right. I tried looking it up I really did. And nothing is clicking. My question is: What can I do to fix this? the error is : ``` .\Queue.java:26: generic array creation PCB[] res = new PCB[200]; ^ Note: U:\Senior Year\CS451- file uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 error ``` Tool completed with exit code 1

Original source

Related problems