DEV Community

Pavithraarunachalam
Pavithraarunachalam

Posted on

ArrayList in the Java Collection Framework.

ArrayList Methods in java:

In Java, ArrayList is a part of the Java Collections Framework and provides many useful methods to store, manipulate, and retrieve data dynamically.

Commonly used ArrayList Methods:

1. Adding Elements:

  • add(E e)-> Adds the elements at the end

Example:

List.add("Apple");
Enter fullscreen mode Exit fullscreen mode
  • add(int index, E e) → Adds an element at the specified index.

Example:

list.add(1, "Banana");

Enter fullscreen mode Exit fullscreen mode
  • addAll(Collection c) → Adds all elements from another collection.

Example:

list.addAll(otherList);

Enter fullscreen mode Exit fullscreen mode

2.Accessing Elements:

  • get(int index) → Returns the element at the given index.

Examples:

String fruit = list.get(0);

Enter fullscreen mode Exit fullscreen mode

3. Changing Elements:

  • set(int index, E e) → Updates the element at the specified index.

Example:

list.set(1, "Mango");

Enter fullscreen mode Exit fullscreen mode

4. Removing Elements:

  • remove(int index) → Removes the element at the given index.

Example:

list.remove(2);

Enter fullscreen mode Exit fullscreen mode
  • remove(Object o) → Removes the first occurrence of the given element.

Example:

list.remove("Apple");

Enter fullscreen mode Exit fullscreen mode
  • clear() → Removes all elements from the list.

Example:

list.clear();

Enter fullscreen mode Exit fullscreen mode
  1. Searching Elements:
  • contains(Object o) → Returns true if the list contains the element.

Example:

list.contains("Mango");

Enter fullscreen mode Exit fullscreen mode
  • indexOf(Object o) → Returns the first index of the element, or -1 if not found.

Example:

int index = list.indexOf("Banana");

Enter fullscreen mode Exit fullscreen mode
  • lastIndexOf(Object o) → Returns the last index of the element.

Example:

int index = list.lastIndexOf("Apple");

Enter fullscreen mode Exit fullscreen mode
  1. Size and Empty Check:
  • size() → Returns the number of elements in the list.

EXample:

int count = list.size();

Enter fullscreen mode Exit fullscreen mode
  • isEmpty() → Returns true if the list is empty.

Example:

isEmpty() → Returns true if the list is empty.

Enter fullscreen mode Exit fullscreen mode

7. Converting to Array:

  • toArray() → Converts the list to an array.

Example:

Object[] arr = list.toArray();

Enter fullscreen mode Exit fullscreen mode

8. Iteration:

  • iterator() → Returns an iterator to traverse the list.

  • listIterator() → Returns a list iterator for forward and backward traversal.

Example:

Iterator<String> it = list.iterator();

Enter fullscreen mode Exit fullscreen mode

9. Sorting (Using Collections):

Example:

Collections.sort(list);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)