Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists vs Arrays - when to use what? [closed]

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?

like image 785
AnchovyLegend Avatar asked Sep 07 '12 15:09

AnchovyLegend


People also ask

When should I use an array instead of a list?

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.

What are the main reasons for choosing to use a list instead of an array?

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.

Which is more efficient array or list?

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.

Are lists less efficient than arrays?

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.


2 Answers

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.

like image 187
Peter Lawrey Avatar answered Oct 07 '22 07:10

Peter Lawrey


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.

like image 32
srini.venigalla Avatar answered Oct 07 '22 09:10

srini.venigalla