what is ArrayList in java with example?
The ArrayList in Java can have duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
ArrayList in Java is used to store a dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.ArrayList is part of Java’s collection framework and implements Java’s List interface.
What is an ArrayList in Java?
An ArrayList class is a resizable array, which is present in java. util package. While built-in arrays have a fixed size, ArrayLists can change their size dynamically. Elements can be added and removed from an ArrayList whenever there is a need, helping the user with memory management.
Example arraylist in java :
import java.util.ArrayList;
import java.util.List;
public class CreateArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of String
List<String> animals = new ArrayList<>();
// Adding new elements to the ArrayList
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals);
// Adding an element at a particular index in an ArrayList
animals.add(2, "Elephant");
System.out.println(animals);
}
}
What is the difference between Array and ArrayList in Java for example?
ArrayList is part of the collection framework in Java. Therefore array members are accessed using [], while ArrayList has a set of methods to access elements and modify them. An array is a fixed-size data structure while ArrayList is not. ... However, ArrayList only supports object entries, not the primitive data types.
No comments:
Post a Comment