Reputation: 43
i came across this scenario when doing a refactor so i was wondering if there exists any differences between both of them?
For example:
import java.util.List;
import java.lang.reflect.Array;
public Object[] toArray(List<Foo> foos) {
Object array = Array.newInstance(Foo.class, foos.size())
int i = 0;
for(Foo foo : foos) {
Array.set(array, i, foo.getSomeProperty);
i++;
}
return (Object[]) array;
}
As for the other hand
import java.util.List;
public Object[] toArray(List<Foo> foos) {
Object[] array = new Object[foos.size()];
int i = 0;
for(Foo foo : foos) {
array[i] = foo.getSomeProperty;
i++;
}
return array;
}
Is there any actual difference between them? My question goes both for the initialization part as well as for setting the value one
When running tests the results are always the same between them
Upvotes: 0
Views: 1288
Reputation: 110
With the Arrays.newInstance
you can create a generic array of a type which you dont know at declaration time. by doing so you avoid a nasty Object[]
declaration which is crucial for type safety.
For you example I could also write
array[i]=new Bar();
See this this post here.
Upvotes: 1