However, it does not. The error message is: error: generic array creation
The problem is with the line that starts with: this.coeff =
Is there a problem creating generic arrays in Java?
Yes, you're not allowed to create generic arrays in Java. The reason is that arrays are covariant, and generic types are invariant by default. If the language allowed generic array creation, type safety would break.
You solve this by either using a collection type internally, or an object array and then casting the elements to T. Using a collection type definitely is the better choice.
This does not seem safe to me because I think of this.coeff as a pointer and setting it to arguments that are on the stack will cause problems when the method returns. Are you sure it is safe?
Bob
No, this.coeff is a field hiding a reference; it isn't a pointer.
That isn't a method; if it compiles it is a constructor.
Yes, you can have problems because you are passing a reference to a mutable reference type (that array) into the constructor; you should take a defensive copy:-You cannot create a generic array; the compiler never likes new T[...] Minor style thing: the [] operator is applied to the type T not the identifier (variable name): T[] coeff please, not T []coeff Similarly for the ... in the parameter.
And coeff is probably not a good variable name because it is an abbreviation and probably doesn't refer to any coefficients.
If you're going to pass in an array instead of a variable list of parameters to a method/constructor that declares (T... coeff), then yes, you're going to need to make a defensive copy. However, if you pass in a variable argument list, nobody can touch that. At any rate, you can do this if you want to make a defensive copy on entry to your object:
And if you want to hand out defensive copies, you do pretty much the same thing: