본문 바로가기

Programming/Data Structure

Array Introduction for Java

반응형

Array's Size

- In C language, array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you can’t shrink it neither can you expand it. 

 

 

Advantages of using arrays:

- Arrays have better cache locality that makes a pretty big difference in performance.

- Arrays represent multiple data items of the same type using a single name.

 

 

Disadvantages of using arrays:

- You can’t change the size i.e. once you have declared the array you can’t change its size because of static memory allocation. 

- an example of implementation of data structure Stack using array there are some obvious flaw. 

 

 

Application on Array

1. Array sotres data elements of the same data type.

2. Arryas can be used for CPU scheduling.

3. Used to Implement other data structures like stacks, Queues, Heaps, Hash tables etc.

 

 

 

Arrays in Java

- All arrays are dynamically allocated.

- The size of an array must be specified by int or short value and not long.

- The direct superclass of an array type is Object.

- An array can contain primitive (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array.

- For primitive data types, the actual values are stored in contiguous memory locations.

- For class objects, the actual objects are stored in a heap segment.

 

 

 

Instantalting an Array in Java

- The elements in the array allocated by new will automaticaly be initialized to zero (for numeric types), false (for boolean), or null (for reference types).

- Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

 

 

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

// Declaring array literal

 

 // accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
  System.out.println("Element at index " + i + " : "+ arr[i]);

 

 

Arrays of Objects

 Student[] arr = new Student[7]; //student is a user-defined class
// Java program to illustrate creating
//  an array of objects
 
class Student
{
    public int roll_no;
    public String name;
    Student(int roll_no, String name)
    {
        this.roll_no = roll_no;
        this.name = name;
    }
}
 
// Elements of the array are objects of a class Student.
public class GFG
{
    public static void main (String[] args)
    {
        // declares an Array of integers.
        Student[] arr;
 
        // allocating memory for 5 objects of type Student.
        arr = new Student[5];
 
        // initialize the first elements of the array
        arr[0] = new Student(1,"aman");
 
        // initialize the second elements of the array
        arr[1] = new Student(2,"vaibhav");
 
        // so on...
        arr[2] = new Student(3,"shikar");
        arr[3] = new Student(4,"dharmesh");
        arr[4] = new Student(5,"mohit");
 
        // accessing the elements of the specified array
        for (int i = 0; i < arr.length; i++)
            System.out.println("Element at " + i + " : " +
                        arr[i].roll_no +" "+ arr[i].name);
    }
}

Output

Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

 

 

 

Multidimensional Arrays

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
public class multiDimensional
{
    public static void main(String args[])
    {
        // declaring and initializing 2D array
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
 
        // printing 2D array
        for (int i=0; i< 3 ; i++)
        {
            for (int j=0; j < 3 ; j++)
                System.out.print(arr[i][j] + " ");
 
            System.out.println();
        }
    }
}

 

 

Returning Arrays from Methods

- A method can also return an array.

// Java program to demonstrate
// return of array from method
 
class Test
{   
    // Driver method
    public static void main(String args[])
    {
        int arr[] = m1();
         
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i]+" ");
     
    }
 
    public static int[] m1()
    {
        // returning  array
        return new int[]{1,2,3};
    }
}

 

 

Cloning of arrays

// Java program to demonstrate
// cloning of one-dimensional arrays
 
class Test
{   
    public static void main(String args[])
    {
        int intArray[] = {1,2,3};
         
        int cloneArray[] = intArray.clone();
         
        // will print false as deep copy is created
        // for one-dimensional array
        System.out.println(intArray == cloneArray);
         
        for (int i = 0; i < cloneArray.length; i++) {
            System.out.print(cloneArray[i]+" ");
        }
    }
}

Output

false
1 2 3 

 

// Java program to demonstrate
// cloning of multi-dimensional arrays
 
class Test
{   
    public static void main(String args[])
    {
        int intArray[][] = {{1,2,3},{4,5}};
         
        int cloneArray[][] = intArray.clone();
         
        // will print false
        System.out.println(intArray == cloneArray);
         
        // will print true as shallow copy is created
        // i.e. sub-arrays are shared
        System.out.println(intArray[0] == cloneArray[0]);
        System.out.println(intArray[1] == cloneArray[1]);
         
    }
}

Output

false
true
true

 

반응형

'Programming > Data Structure' 카테고리의 다른 글

Java reverse array  (0) 2022.03.23
포인터 배열 구조체  (0) 2022.03.22
스택과 힙의 차이  (0) 2022.03.14
스택과 큐(Stacks and Queues) 알고리즘  (0) 2022.03.07
List data structure  (0) 2022.02.10