Creating a method or function and you need to return a number of objects, which do you use a List or an Array?
Both have their uses, and maybe your project’s design would add weight to which you decide to do. Setting that factor aside let’s look at our options on what we can do.
Array
It gives you access to the member variable length. A simple int that tells you the number of items in the array. This is great if your array is not null, you can directly access the length of the array to determine it’s size
Secondly it gives you access to the clone() method to create a copy of the array. This is a shallow copy of the array. If you are looking at implementing your own sort, being able to easily create a shallow copy of the array could be extremely beneficial.
Then an Array is also lighter weight. Fewer objects for garbage collection when it goes away. This is extremely important when you are working on real-time projects or on hardware with limited processing or memory.
List
I have to admin I’m extremely partial to returning lists, even if the list is empty. Why?
mylist.stream()......
Java 8 was a game-changer with the addition of streams. With everything you can do with a stream, having your method/function return a stream or empty stream at the least is extremely helpful. It really does simplify when you can do something like this:
this.getOpenCustomer().stream().filter(customer -> customer.getAge() > 18).sorted(Comparator.comparing(Customer::getLastName)).collect(Collectors.toList());
Streams do offer great flexibility. However, they are not the only reason to return a List. With a list, it’s easy to intersections, unions, and unique entries with another list. Combining two lists together is a simple method call.
Overall a List provides the greater flexibility, than an array. If you need an array, then you can always:
this.getOpenCustomer().stream().toArray(Customer[]::new);
Discover more from GhostProgrammer - Jeff Miller
Subscribe to get the latest posts sent to your email.