2
\$\begingroup\$

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?

dfhwze
14.1k3 gold badges40 silver badges101 bronze badges
asked Sep 19, 2019 at 7:18
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Perhaps it has to do with boxing and variance that generics are used. \$\endgroup\$ Commented Sep 19, 2019 at 8:12
  • 2
    \$\begingroup\$ did you try to call the method with a List<String> arg? \$\endgroup\$ Commented Sep 19, 2019 at 11:28
  • \$\begingroup\$ You would have to cast the result back to whatever type. This feels like a hack \$\endgroup\$ Commented Sep 19, 2019 at 18:42
  • 1
    \$\begingroup\$ See stackoverflow.com/questions/34939499/… \$\endgroup\$ Commented Sep 19, 2019 at 19:37

1 Answer 1

1
\$\begingroup\$

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:

  1. No casting needed
  2. Can be used any where with any kind of list.
answered Sep 20, 2019 at 20:34
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.