Mark As Completed Discussion

ArrayList Operations

ArrayLists provide a wide range of operations that can be performed to manipulate and work with the elements stored in the list. Here are some common ArrayList operations:

Adding Elements

To add elements to an ArrayList, you can use the add() method. This method appends the specified element to the end of the list. For example:

TEXT/X-JAVA
1ArrayList<String> names = new ArrayList<>();
2names.add("Alice");
3names.add("Bob");
4names.add("Charlie");

Accessing Elements

You can access the elements of an ArrayList by their index using the get() method. The index starts from 0 for the first element and goes up to size() - 1 for the last element. For example:

TEXT/X-JAVA
1String firstElement = names.get(0);
2String secondElement = names.get(1);

Modifying Elements

If you want to modify an element at a specific index in the ArrayList, you can use the set() method. This method replaces the element at the specified index with the new element provided. For example:

TEXT/X-JAVA
1names.set(2, "David");

Removing Elements

To remove an element from the ArrayList, you can use the remove() method. This method removes the element at the specified index from the list. For example:

TEXT/X-JAVA
1names.remove(1);

Other Operations

Aside from the mentioned operations, ArrayLists also provide other useful methods such as:

  • size(): Returns the number of elements in the ArrayList.
  • isEmpty(): Checks whether the ArrayList is empty or not.
  • contains(): Checks whether the ArrayList contains a specific element.

ArrayLists offer flexibility and convenience in performing various operations on the elements stored in the list. These operations allow you to manipulate and work with the data in different ways based on your specific requirements and use cases.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment