Java Data Structures

Introduction

Java Data Structure

Contents

  1. Array
  2. Reference Type vs Value Type
  3. List and ArrayList

1. Java Array

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

package anote;

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

        int[] myVar = new int[10];
        double[] myDouVar = { 50.2, 40.3, 60.7, 90.0 };
        String[] myCars = { "BMW", "KIA" };

        myVar[5] = 30;
        System.out.println(myVar[5]);
        System.out.println(myCars[1]);
        System.out.println("---");
        for (int i = 0; i < myDouVar.length; i++) {
            System.out.println(myDouVar[i]);
        }
    }
}
30
KIA
---
50.2
40.3
60.7
90.0

Value Type vs Reference Type

All the primitive types are value types, in other words, they hold a value. Unlike primitive types, an array is a reference type and String is also a reference type.

Values Type

package anote;

public class Main {
    public static void main(String[] args) {
        int theValue = 10;
        int anotherValue = theValue;

        System.out.println("theValue is " + theValue );
        System.out.println("anotherValue is " + anotherValue );

        anotherValue++;

        System.out.println("theValue is " + theValue );
        System.out.println("anotherValue is " + anotherValue );
    }
}
theValue is 10
anotherValue is 10
theValue is 10
anotherValue is 11

The value type is a single space in memory is allocated to store the value, thus the values directly holds the values.

the example (theValue and anotherValue) holds the values independently.

Reference type

package anote;

import java.util.Arrays;

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

        int [] theArray = new int [5];
        int [] anotherArray = theArray;

        System.out.println("theArray is " + Arrays.toString(theArray));
        System.out.println("anotherArray is " + Arrays.toString(anotherArray));
        anotherArray[0] = 1;

        System.out.println("theArray is " + Arrays.toString(theArray));
        System.out.println("anotherArray is " + Arrays.toString(anotherArray));
    }
}
theArray is [0, 0, 0, 0, 0]
anotherArray is [0, 0, 0, 0, 0]
theArray is [1, 0, 0, 0, 0]
anotherArray is [1, 0, 0, 0, 0]

The Reference type, like array or classes. So whenever you see the new keywords that you are creating a new objects.

The reference type used by reference. The reference holds a reference or an address of the objects, but not objects itself. With reference types, we are using a reference to control the object in memory. So, we can not access the object directly.

3. List and ArrayList

ArrayList inherits from List

Leave a Reply

Your email address will not be published.

ANOTE.DEV