Java Collection - Array

 

if we want to create 1000 variables with the same datatype we need to declare 1000  new variables and it's very difficult for programmers to deal with such types of variables. to overcome this problem Collection framework is introduced.

The collection is a set of interfaces and classes to represent data structure and Algorithm. 

Array : 

  • the Array store data by indexing.
  • the index will start from 0
  • Array in an indexed-based collection that contains a fixed number of homogenous data elements.
  • We can declare an Array
    Student[] s = new Student[1000];

Limitation: 

  • The array is a fixed size so once we create an Array we can not change the size of the Array.
  • The array can hold only homogeneous data type which means Array can only contain the same data type values.
  • the Arrays are a fixed-size index-based collection due to there being chances of memory waste. for example, if we create an Array with 1000 sizes and in programming, we only add 100 values in the array then there is 900 variable space will waste.
  • The below code will give compile time error because the array will contain only the same data type values.

  • Student[] s = new Student[1000];
    s[0] = new Student("1","Nilesh");
    s[1] = new Customer("1","Nilesh");
  • To overcome the above problem we can create an Array of Object.

  • Object[] s = new Student[1000];
    s[0] = new Student("1","Nilesh");
    s[1] = new Customer("1","Nilesh");
  • The array is an underlying data structure because for every requirement programmer needs to write code explicitly. which increases the complexity of the programmer. For Example Sorting. If we want to add sorting on Array then Programmer needs to write code for sorting and it's a special headache for developers.

Advantages of Array:

  • We can represent the multiple values in a single variable so which can reduce programming complexity and increase code readability.

Comments

Popular posts from this blog

How to do @Async operation in spring boot

Coding Problem 3 - Weather Observation Station 7 [HackerRank - SQL]

Date Range Picker In Angular 10