× Home

Arrays and ArrayList

Why do we need Arrays?

It was simple when we had to store just five integer numbers and now lets assume we have to store 5000 integer numbers. Is it possible to use 500 variable? NO
So, to handle this situations, in almost all programming language we have a concept called Array.

Array

Array is a data structure use to store a collection of data.

Syntax:

                        

                            datatype[] variable_name = new datatype[size];
                        
                    

Examples

                        

                            // we want to store roll numbers
                            int[] rollnos = new int[5];
                            // OR
                            int[] rollnos = {1,2,3,4,5};
                        
                    

Internal working of array:

int[] rollnos; → declaration of array.

rollnos are getting defined in stack

rollnos = new int[5]; → initialization

actual memory allocation happens here. Here, object is being created in heap memory.

The above concept is known as Dynamic memory allocation which means at runtime or execution time memory is allocated

Internal Representation of Array

  • Internally in Java, memory allocation totally depends in on JVM whether it be continous or not!
  • Reasons
    1. Objects are stored in heap memory
    2. In JLS (Java Language Specification) it is mentioned that heap objects are not continous
    3. Dynamic memory allocation. Hence, array objects in Java may not be continous (depends on JVM)

Index of an array

new keyword:

int[] arr = new int[5];
used to create an object

  • It will create an object in heap memory of array size 5

  • Some Properties
    • If we don't provide values in the array, internally by default it store [0, 0, 0, 0, 0] for above size array.
    • Arrays are stored in heap memory.
      • Primitive (int, char etc) are stored in stack.
      • All other objects are stored in heap memory.
    • In an array, since we can change the objects, hence they are mutable.
      • Strings are immutable

Arrays.toString(array) → internally uses for loop and gives the output in proper format.

                        

                            import java.util.Arrays
                            public class Arrays{
                                psvm(){
                                    int[] arr = {1,2,3,4,5};
                                    sout(Arrays.toString(arr));
                                } 
                            }                            
                        
                    

output

[1, 2, 3, 4, 5]

2D Array

arr[0] = [22, 33, 44]
arr[0][2] = 44

Printing 2d Array

                        

                            import java.util.Arrays;

                            public class MultiDimensionArr {
                                public static void main(String[] args) {

                                    int[][] arr = {
                                        {1,2,3},
                                        {4,5,6},
                                        {7,8,9}
                                    };

                                    // first way
                                    for (int i = 0; i < arr2.length; i++) {
                                        for(int j = 0; j<arr2[i].length;j++){
                                            System.out.print(arr2[i][j]+" ");
                                        }
                                        System.out.println(" ");
                                    } 
                                    System.out.println(Arrays.toString(arr2));
                                    
                                    // second way
                                    // for each method
                                    for(int [] a : arr2){
                                        System.out.println(Arrays.toString(a));
                                    }
                            
                                }
                            }                            
                        
                    

ArrayList

Arraylist is a part of collection framework and is present in java.util.package. It provide ws with dynamic arrays in Java. It is slower then standart arrays.

Syntax

                        

                            import java.util.ArrayList;

                            ArrayList<Integer> list = new ArrayList<>();
                            // Integer - class wrapper
                        
                    

Internal working of ArrayList

  • Size is fixed internally
  • Suppose arraylist gets filled by some amount
    • It will make an arraylist of say double the size of arraylist initially
    • Old elements are copied in the new array
    • old ones are deleted

methods in ArrayList

  • someArrList.size() → to get the length of the arraylist
  • someArrList.get(2) → to get the element sitting on 2 index.

Why we need ArrayList

Case

Elements in 2D array

                            

                                int[][] multiArr = {
                                    {1,2,3},
                                    {4,5},
                                    {6,7,8,9,10}
                                }
                            
                        

↑ Reason why we have to specify number of rows when we initialize 2D array is that we need fix number to define rows and number of column doesn't matter as it can be different.

  • Storing a 2D array with fix number of row and coloum is easy during runtime
  • But to storing a 2D array whose number columns are not fixed for each row is difficult
  • That's why we use ArrayList
                            

                                // 1D array
                                import java.util.ArrayList;

                                public class ArrayListEx {
                                    public static void main(String[] args) {
                                        // we use arraylist when we don't know how much is size of row
                                        // syntax
                                        // ArrayList name = new ArrList<>();
                                        ArrayList list = new ArrayList<>();
                                        list.add(99);
                                        list.add(100);
                                        list.add(122);
                                        list.add(123);
                                        System.out.println(list);
                                        list.set(0,101);
                                        System.out.println(list);
                                    }
                                }
                                
                            
                        
                            

                                // 2D array 
                                import java.util.ArrayList;
                                import java.util.Scanner;
                                
                                public class MultiArrList {
                                    public static void main(String[] args) {
                                        Scanner in = new Scanner(System.in);
                                        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
                                
                                        // Initialization
                                        for(int i = 0; i<3 ; i++){
                                            list.add(new ArrayList<>());
                                        }
                                
                                        // add elements
                                        for (int i = 0; i < 3; i++) {
                                            for (int j = 0; j < 3; j++) {
                                                list.get(i).add(in.nextInt());
                                            }
                                        }
                                
                                        // Print
                                        System.out.println(list);
                                    }
                                }