I am relatively new to Java and over the years I had to solve all sorts of programming problems where the number of data that needs to be collected is really unknown to the programmer.
Is it a good convention to use Lists to collect strings or integer values when the programmer has no way of knowing the amount of variables that needs to be collected? Or is there a better way to handle this using dynamic arrays in Java?
Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.
Lists can easily grow in size, and you can add and remove elements in the middle of the list easily. That cannot be done with arrays. You need to consider what you need the list for though. If you don't think the list is going to change a lot, then use an array instead.
The array is faster in case of access to an element while List is faster in case of adding/deleting an element from the collection.
Better use of Memory: From a memory allocation point of view, linked lists are more efficient than arrays. Unlike arrays, the size for a linked list is not pre-defined, allowing the linked list to increase or decrease in size as the program runs.
If in doubt, using a List is likely to be a better choice even if you know the length.
Using an array can be better for performance, but you need to be an expert to know when this is a good idea, and when it just makes your solution more complicated.
BTW: There is no such thing as dynamic arrays
in Java.
You are doing it right.
List is an Interface and ArrayList is the implementation. If you do not care much for OO mambo-jumbo, here is how you can understand it.
List is the way you want to deal with the "system". You don't care much for anything else.
But the "system" has the freedom to implement it in several ways! ArrayList, LinkedList, Vector etc.
Once you understand this separation, then try to glean the differences and nuances between these implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With