1

If I defined my own generic array with this constructor:

public PublisherGenericArray(Class<E> c, int s)
{   
    // Use Array native method to create array  
    // of a type only known at run time
    @SuppressWarnings("unchecked")
    final E[] a = (E[]) Array.newInstance(c, s);
    this.a = a;
}

How do I create an object that satisfies the first parameter (class c)?

Basically:

PublisherGenericArray <String> newArray = new <String> PublisherGenericArray(???,newSize);

What would go in the first parameter labeled "???"

1
  • Your <String> in new <String> Publis... serves no purpose here. Commented Aug 4, 2015 at 0:16

2 Answers 2

2
PublisherGenericArray<String> newArray = new PublisherGenericArray<String>(String.class, newSize);
Sign up to request clarification or add additional context in comments.

Comments

1

The first parameter of your construction is a class of the parametrised type.

The parametrised type is the invocation of the generic type. For example

Foo<T> is a generic type, while in

Foo<Integer> t;

the Foo<Integer> is a parametrised type.

In your code, E is a parameter type (variable type)

there are infinity number of possible constructions. To list some:

PublisherGenericArray<Integer> t = new PublisherGenericArray<Integer>(Integer.class, 3);
    PublisherGenericArray<String> tt = new PublisherGenericArray<String>(String.class, 3);
    PublisherGenericArray<NullPointerException> ttt = new PublisherGenericArray<>(NullPointerException.class, 3);

notice in the ttt, i have used The Diamond and it just works with java SE 7 and later

You can also create your parametrised type by doing the invocation on a raw type as well

class A<T> {
        }
        PublisherGenericArray<A> tttt = new PublisherGenericArray<A>(
                A.class, 4);

1 Comment

Good examples! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.