4
\$\begingroup\$

I created a method to return a copy of List<T>, basically I convert the List<T> into an array T[], then perform the copy with the arrayCopy(T[]) method and back convert again in List<T>.

I want to know if the code will be run successfully in different scenarios and it is good in performance or is there a way to do it better.

public static <T> List<T> getCopyOfList(List<T> list) {
    return Arrays.asList((T[]) arrayCopy(list.toArray()));
}

public static <T> T[] arrayCopy(final T[] original) {
    return Arrays.copyOf(original, original.length);
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You're not creating a copy of a List. You're creating a new list with the same elements as the original list. The difference is important as "a copy" would imply that the result is a copy of the original, sharing the same object type and the elements. As such this helper method is a bit useless as the caller can not choose the correct list implementation for their use case. So I ask the same question as Eric Stein: why not just use the copy constructor? Can you elaborate on why you need these methods? \$\endgroup\$ Nov 23, 2021 at 11:22

2 Answers 2

11
\$\begingroup\$

Given that arrayCopy has exactly one line, it's not clear that there's much value in having it extracted as a method.

toArray() is documented to return a safe array, so there is no need to copy it.

getCopyOfList returns a fixed-length list without documenting that fact. Clients may be surprised that optional List methods such as add() and remove() are not supported.

Why wouldn't clients prefer to use the copy constructors available on LinkedList and ArrayList? Those would allow clients to control the type of List they're working with, and the call is part of the public API.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the feedback, I will adapt my implementation. \$\endgroup\$
    – TimeToCode
    Nov 23, 2021 at 16:38
2
\$\begingroup\$

Don't create Rube Goldberg machines. There is an easier way to accomplish what you want:

public static <T> List<T> getCopyOfList(List<T> list) {
    
    return new ArrayList<T>(list);
    
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.