Q: Write a method that transforms a list into an array (don't use collections or already implemented methods in lists, make your own method)
I've come with this solution:
public static Object[] toArray(List<Object> list) {
Object[] arr = new Object[list.size()];
for (int i = 0; i < list.size(); ++i) {
arr[i] = list.get(i);
}
return arr;
}
I've read this Convert a generic list to an array, and seems like they overcomplicated the solution. Why they choose to use generics? Is there something wrong with my approach?
1 Answer 1
I think, as per your solution, in every case you'll get a list of objects not the list of actual class you need. If you want to use this array you have to cast the object to your desired class. To do that you have to check if you can cast the object to your desired class as the down casting can cause error if you don't use instanceOf.
In short you have to do all this by your self every time you want to use this method for any kind of list.
On the other hand the generic code will always return you the array of your class not object.
I think the generic code has 2 advantage over your code which are:
- No casting needed
- Can be used any where with any kind of list.
Explore related questions
See similar questions with these tags.
List<String>
arg? \$\endgroup\$