Introduction of Collection Framework

Limitations of array

Array represents a finite sequence of similar type of data elements. We cannot change the size of an array once it is created.

Suppose we have two classes i.e. Employee and Student. We have created employee array and wanted to store Student object into an array of Employee type then we will get compile time error.

Employee e1[]=new Employee[50];
      e1[0]=new Employee();
      e1[1]=new Employee();
      e1[2]=new Student();//Compile time error.
      ..
      ..
     e1[49]=new Employee(); 
     e1[50]=new Employee(); //RTE-ArrayIndexOutOfBound

To overcome this problem, we can create an Object type array and we can store any type of object.

Object O1[]=new Object[5];
O1[0]="Raj";
O1[1]= new Employee();
O1[2]=1; // O1[2]=new Integer(1);
O1[3]='a';
O1[4]=new Student();

But in java, there is no predefined methods support available to store and manipulate data element of an array like traversing, sorting, adding, removing etc.

We need to write each and every logic for any operation.

                                                       
class Employee
{
}
class Programmer
{
 int id;
 String ename;
 float salary;
 
public static void main(String args[])
	 {
	  System.out.println("Hello");
	  Programmer p1[]=new Programmer[50];
      p1[0]=new Programmer();
      p1[1]=new Employee();
 
	 }
	} 
//O/P-Compile Time Error-Employee cannot converted into Programmer	
                                                      
class Employee1
{
	 public static void main(String args[])
	 {
	  System.out.println("Hello");
	  Object O[]=new Object[5];
	  O[0]=new Employee1();
      O[1]=new Student();
      O[2]=new Integer(1);
      O[3]=new String("Raj");
	 }
	 
}
//Compile Time Success and Runtime Success.	
Footer with Map

Top