Hey guys,
I understood how to declare Lists and use them, but I am curious what´s the best way to declare them? I have seen many different examples and wonder if there are big differences between them and if so, what advantages each declaration has and when to use which? Have a look:
I was not able to display the String between <> in this editor, that´s why I used the image to show you.
So the first one uses List before the variable name and in the object declaration uses ArrayList (and nothing between <>). The second uses two times the ArrayList. And the third one uses two times the String in the <>.
I did not encounter any problem so far, because apparently all seem to work fine and very similar, I am just asking myself if there is a difference between them and which one you would recommend to use?
Thanks a lot,
Tim
Best way to declare Lists
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
horst
14 April 2020, 09:26solution
Admittedly, my knowledge of the subtleties of declaring collections in Java is quite poor, but as a starting point: In general it is considered best practice to declare them like in your first example:
ArrayList on stackoverflow that might answer some of your questions.
Here, the more general List interface is chosen as a data type to store your ArrayList. As far as I understand this is mostly done to simplify maintaining and reworking your code later on. The program expects a List and does not care which one (ArrayList, LinkedList, Stack, ...). This way you can easily change the type of your list later on in the process, without having to redo all the individual uses of your list.
PS: Here's a very nice discussion about declaring an +2
DeltaPilot12
15 April 2020, 09:09
Thanks a lot! That answered my question indeed!
0