Programming |
We can declare one integer value by taking one variable like this:
int i =10;
But if we want to declare 100 values, then taking 100 variables to declare 100 values will be very troublesome for the developer. They will have a hard time managing all those variables and the readability of the code will be not very good. To fix this problem we can use Arrays.
By using Arrays we can declare any number of values by using a single variable. Suppose we want to declare 100 integer values. We can achieve that by using the following code:
int[] intArr = new int[100]
In arrays, the values are differentiated by the use of indexes. Here is an example to add a few values to the above declared array of integers:
intArr[0] =9;
intArr[1]=10;
.
.
.
intArr[99]=1;
Note: The numbers inside the square brackets([]) are the index at which the values are stored. The index of arrays start from 0 and end at n-1, n being the size of the array.
By using arrays we’ve improved the readability of code.
But like everything Arrays also have limitations. Here are some of them:
Employee[] empArr = new Employee[10];
In Employee Array, we can only declare Employee objects. If we try to add any other type of object like Student or something else, we’ll get compile-time error.
In order to overcome these limitations of the Arrays, we need Collection Framework. Here are some advantages of Collections over Arrays: