简体   繁体   中英

Java: Generic array creation error?

Getting a Generic array creation error on a non generic array, I think?

So, this code works fine, pretty straight-forward.

public class test {
  private subTest[] subTests;
  private class subTest {

  }

  public test(int size) {
    subTests = new subTest[size];
  }
}

But what I am actually trying to do is something more like this:

public class test<T> {
  private subTest[] subTests;
  private T[] arrayOfGenerics; 

  private class subTest {

  }

  public test(int size, int size2) {
    arrayOfGenerics = (T[]) new Object[size];   //This line works fine
    subTests = new subTest[size2];              //This line is the one giving me a 'Generic array creation' error
  }
}

subTest is an inner class of test , so the type parameter of test is visible from within subTest . Therefore, you are trying to create an array of generic type

test<T>.subTest[]

You can solve this by making the class subTest a static nested class instead:

private static class subTest

If you do this, the type of the array is just

test.subTest[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM