A possible way for generic type arrays?
Does creating an array of generic objects, in this fashion, has any downsides or performance issues?
Que开发者_开发技巧ryObjects instances[] = (QueryObjects<String,String,String>[]) new Object[10];
Edit: I was even thinking if I could instead rely on this:-
QueryObjects instances[] = new QueryObjects[10];
The primary reason for this being, I do not want to fix the generic to <String,String,String>
because sometimes it can also be like <Integer,Integer,Integer>
for some elements of array. So I would like to give it as a runtime choice. Since this is mostly for application's internal work and not for any client side input, perhaps I should not be facing the danger of wrong inputs.
Your code will generate a ClassCastException
at run time.
You should create an array of type QueryObjects[]
and cast it to QueryObjects<String, String, String>[]
, or in the future, if you need to create an array of a variable type (e.g., T[]
), use reflection: How to create a generic array in Java?
Creating it in this way does have a downside: you now have what is really an array of any kind of Object
disguised as an array of QueryObjects
. If someone else has a reference to the same array (and know that it is an Object[]
), they could put some Object
into it, e.g. a String
, and then the program will throw a ClassCastException
when you try to access that String
through your reference to the array. Solution: create it like this:
QueryObjects<String, String, String> instances[] = new QueryObjects[10];
the "righteous" way is
QueryObjects<?,?,?>[] instances = new QueryObjects<?,?,?>[10];
the raw way is just fine:
QueryObjects[] instances = new QueryObjects[10];
notice the type declaration:
Type[] var
not
Type var[]
I don't care why Java allows the 2nd syntax, it still doesn't make any sense.
It begs the question "If you're using generics, why use an array instead of an a typed structure?"
Instead of trying to achieve QueryObjects[]
and doing it poorly, why not create a type for it? Then you can add whatever methods you want. Yay object orientation!
class QuerySet<O extends QueryObjects<A,B,C>> {
O[] objects;
}
精彩评论