Array and Collections difference

Difference

  1. Arrays can be used for primitive (int, double, float, byte, etc.) and non-primitive (Integer, String, Objects, etc.) data types. Whereas Collections can be used for only non-primitive (Integer, String, Objects, etc.) data types.
    int[] a = {1,2,3} // Array of primitive type
    Class[] c = {obj1, obj2, obj3} // Array of non primitive type
    ArrayList al = new ArrayList()
    al.add(obj1) // obj1 is an object of a Class.
    al.add(10) // 10 -> Integer i = new Integer(10) is an object of an Integer class which is non-primitive and is a wrapper class made for int values.
    al.add('2')
  2. Arrays can be used to save only same type of data i.e. homogenous data. Whereas Collections can be used to save different types of data i.e. heterogenous data.
  3. The size of the arrays are fixed. We cannot increase or decrease the size of an array at runtime. But the size of the collections are not fixed. If required we can increase or decrease the size of the collections at runtime.
  4. Arrays are in built feature of Java. We have to build algorithms to manipulate elements of an array like for sorting, searching. Collection framework is an API, which provides predefined classes, interfaces and methods.


Comments

Popular posts from this blog

Collections in Java

Exception Handling

OOPS Concept in Java