Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between an array and any collection from the java Collection framework?

As the title say I am looking into the "Differences between an array and any collection from the java Collection framework".

Thought it's high level enough to provide some good understanding to a few (or many) of us who know too little about this or need to think far too long to come up with a interesting answer

So far, I have come up with:

  1. Collection framework classes either use array underneath or use more complex data structure. When an array is simply...an array
  2. Array does not have methods (no API) such as the ones provided by Collection classes.

Please correct me if these were incorrect assumptions, and of course add your own answers

like image 299
Adrien Be Avatar asked Nov 13 '12 13:11

Adrien Be


People also ask

What is the difference between a regular array and collections framework such as ArrayList?

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects.

Is array a collection in Java?

What is an Array in Java ? An Array is collection of indexed and fixed number of homogeneous (same type) elements.


2 Answers

They are virtually unreleated, except to say they both store a group of values.

From a capability perspective, while both can store references to objects:

  • Arrays can store primitives
  • Collections can not store primitives (although they can store the primitive wrapper classes, such as Integer etc)

One important difference, commonly not understood by programmers new to java, is one of usability and convenience, especially given that Collections automatically expand in size when needed:

  • Arrays - Avoid using them unless you have to
  • Collections - Use them in preference to arrays

Arrays are ultimately the only way of storing a group of primitives/references in one object, but they are the most basic option. Although arrays may give you some speed advantages, unless you need super-fast code, Collections are preferred because they have so much convenience.

like image 187
Bohemian Avatar answered Oct 17 '22 08:10

Bohemian


There are 5 differences between Array and Collection as given below :

  1. Arrays are fixed in size, whereas some Collections are grow-able in nature.

  2. Arrays store homogeneous data. Collections store both homogeneous as well as heterogeneous data.

  3. In Arrays, there are no underlining data structures, whereas Collections have underlining data structures.

  4. Arrays are recommended for performance, whereas Collections are not.

  5. Arrays use more memory space as compared to Collections.

like image 30
SouravK Avatar answered Oct 17 '22 06:10

SouravK