Dynamic Array in Java

 In Java, a dynamic array is implemented using the ArrayList class, which is part of the Java Collections framework. An ArrayList is similar to an array, but it automatically resizes itself when elements are added or removed. Here's an example:

java
import java.util.ArrayList; public class DynamicArrayExample { public static void main(String[] args) { // create an ArrayList ArrayList<String> names = new ArrayList<>(); // add elements to the ArrayList names.add("Alice"); names.add("Bob"); names.add("Charlie"); // get the size of the ArrayList int size = names.size(); System.out.println("Size of ArrayList: " + size); // access elements of the ArrayList String first = names.get(0); System.out.println("First element: " + first); // remove an element from the ArrayList names.remove(1); System.out.println("Updated ArrayList: " + names); } }

In this example, we create an ArrayList called names and add three elements to it. We then get the size of the ArrayList and access the first element using the get() method. Finally, we remove the second element using the remove() method and print the updated ArrayList.

Note that ArrayLists can only hold objects (not primitive types like int or double). To work with primitive types, you can use the corresponding wrapper classes (e.g., Integer, Double, etc.) or use an external library like Trove.

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java