You must not (*) do this in one method. Item[] and List<Item> are unrelated types.
You must make one of the overloads the other: either something(Item... items) calls something(List<Item>) , or something(List<Item>) calls something(Item... items) .
Of the two parameters, it is better to overload the array to cause the list to be overloaded:
public void something(Item... items) { something(Arrays.asList(item)); }
This is cheap because it does not copy the array, but rather wraps it: creating a List is O(1) .
If you were to call array overload from list overload:
public void something(List<Item> items) { something(items.toArray(new Item[0])); }
That would be more expensive since a call toArray should create and populate an array: this is an O(n) operation, where n is the size of the list. However, it has a slight advantage in that something cannot replace the contents of the List , since any updates to the array are simply discarded after execution.
(*) You can, but it would be very rude, and not safe, since you would need to accept the Object parameter, since there is no other common super-type List<Item> and Item[] ; and you still have to repeat the loops for the two types; and you have to handle the ability to transfer a completely unrelated type (at runtime):
public void something(Object obj) { if (obj instanceof List) { for (Object element : (List<?>) obj) { Item item = (Item) element; // Potential ClassCastException. doStuff(); } } else if (obj instanceof Item[]) { for (Item item : (Item[]) obj) { doStuff(); } } else { throw new IllegalArgumentException(); } }
What a mess. Thank the creator for the overload.
Andy Turner Jan 27 '17 at 15:14 2017-01-27 15:14
source share