Java List toArray(T[] a) implementation -
i looking @ method defined in list interface:
returns array containing of elements in list in correct order; runtime type of returned array of specified array. if list fits in specified array, returned therein. otherwise, new array allocated runtime type of specified array , size of list. if list fits in specified array room spare (i.e., array has more elements list), element in array following end of collection set null. useful in determining length of list if caller knows list not contain null elements.
<t> t[] toarray(t[] a);
and wondering why implemented way, if pass array length < list.size(), create new 1 , return it. therefore creation of new array object in method parameter useless.
additionally if pass array long enough using size of list if returns same object objects - no point in returning since same object ok clarity.
the problem think promotes inefficient code, in opinion toarray should receive class , return new array contents.
is there reason why not coded way?.
as mentioned others, there couple different reasons:
- you need pass in type somehow, , passing in array of specified type isn't unreasonable way it. admittedly, might nice if there version pass in class of type want too, speed.
- if want reuse array, can keep passing in same one, rather needing create new 1 each time. can save time , memory, , gc issues if need many, many times
Comments
Post a Comment