Introduction To Dynamic Array

In general Array has fixed capacity .  Array that we are talking about is linear array and we need to give size of the array when we initialize it  , which is wasteful and inconvenient sometimes.


Most programming languages offer built in dynamic array. Which is a random access list data structure with variable size .

We have ARRAYLIST in Java which is similar to Vector C++.

/**
 *
 */
package com.techyield.operationsinarray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class OperationsInDynamicArray {

/**
* @param args
*/
public static void main(String[] args) {
       
// Initialize
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 ; // here l2 == null

// Cast an array to List
Integer[] array = {1,2,3,4,5,6,7,8};
l2 = new ArrayList<>(Arrays.asList(array));

// Make a copy

List<Integer> l3 = l2;  // another reference to l1
List<Integer> l4 = new ArrayList<>(l2); // make an actual copy of l2

// Length

System.out.println("The size of list is "+l2.size());

// Access Element
System.out.println("The first element in l2 is "+l2.get(0));

// Iterate the linkedList
System.out.println("The contents of l2 are : ");
for(Integer a : l2) {
System.out.println(a);
}
System.out.println(" Version2 ............");
for(int i =0 ; i < l2.size(); i++) {
System.out.println(" "+l2.get(i));
}
System.out.println();

// Modify the element
l2.set(0,5);
System.out.println("l2.get(0)"+l2.get(0));
// Modify the element
l2.set(0, -1);
System.out.println("l2.get(0)"+l2.get(0));
// here l3 refers to l2 so modifying l2 modifies l3
// Sort
Collections.sort(l2);
// Add a new element at the end of the ArrayList
l2.add(9);

l2.add(2,5);

// Remove an element

l2.remove(l2.size()-1);

for(int u : l2) {
System.out.println(u);
}




}

}








No comments:

Post a Comment

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...