Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Arrays vs Collections?

I used to use arrays all the time but now I just stumbled upon collections.

Is there any reason to use arrays as collections seem superior in almost every way and I've read some articles on stack overflow which seem to agree with me.
(Aug 3, 2016 12:01 AM)Folks Wrote:  Is there any reason to use arrays as collections seem superior in almost every way and I've read some articles on stack overflow which seem to agree with me.

Depends on what you're using it for and what collection it is. For example ArrayList uses delegation on an array, while LinkedList uses linked nodes.

Getting the Nth element from an array is possible with O(1) complexity, but getting the Nth element from a LinkedList is done in O(n) complexity (if it's not circularly linked, in which case it is still worse than O(1)), as you have to traverse the link in order to find your element before you can return it.
I suggest you take a course in datastructures if your school offers it, or read up on it online. Once you understand how the different structures work and their pros and cons it's easier to choose which one you need.
Following more on what Rewbert said, there's a great site to find our the best kind of datastructure to use for your purpose:
http://bigocheatsheet.com/

I don't really use it anymore but it's helpful. It also has stuff for sorting algorithms and more
Remember this fist rule: Use arrays when you know the length beforehand, otherwise use collections.

There are exceptions of course, but I will not mention them here.
Arraylists have an amortized complexitity of O(1), though.
Sometimes you will still have to use array - like for a String.split("[ ]+"); method
[Image: IipsxcD.jpg]

All the above are good answers.
For the general rule, use existing optimal code/classes when you can, but know your data set is hugely important. Don't reinvent code unless you really need to. Arrays are extremely useful at low level when you know a set data length in advance. Otherwise big Okicks in as previous posts implied and you are better off using optimized code (unless you really need something specific)
Cheers


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by pzychonautJun 8, 2023 05:03 PM 5 178 Jun 8, 2023 05:03 PM
Last Post: padrino
[C] by EmacsSucksButILikeItJun 4, 2022 11:03 PM 1 222 Jun 4, 2022 11:03 PM
Last Post: unazed
[Java] by PsychoJul 3, 2021 11:15 PM 24 1,975 Jul 3, 2021 11:15 PM
Last Post: Lookdadon