AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Main methods arraylist

In this article, we will see the use and main methods of ArrayList in Java as a tool for facilitating and storing elements. We could define an ArrayList in Java, which is located in the java.util package, as a dynamic array that allows us to store elements without a limited size like an array.

An ArrayList implements the List interface, which allows us to use all its methods.

Main characteristics of ArrayList

Let’s list the main characteristics of ArrayList:

  • ArrayList can contain duplicate elements, which we could say is its most important feature.
  • ArrayList has random access due to the array working with an index base.
  • The insertion order is maintained.
  • It does not allow the use of synchronized.
  • Access to an ArrayList is going to be slower than access to LinkedList.
  • It should be noted that it is not allowed to create ArrayList of primitive types.
  • ArrayList extends AbstractList and implements the List interface.
  • ArrayList has the following declaration in Java.

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

Main methods of ArrayList in Java.

Constructors in ArrayList

We have three different ways to instantiate an ArrayList:

Building an empty ArrayList:

new ArrayList()

Creating an ArrayList with a size:

new ArrayList(int size)

Building an ArrayList with the element type:

ArrayList(Collection<? extends E> c)    

Main methods of an ArrayList

MétodoDescripción
void add(int index, E element)Allows adding an element at a specific position
boolean addAll(Collection<? extends E> c)Allows adding a collection of elements
boolean add(E e)Allows adding an element to an ArrayList
boolean addAll(int index, Collection<? extends E> c)Allows adding a collection of elements from a position in an ArrayList
void clear()Allows clearing an ArrayList
boolean isEmpty()Returns TRUE if the ArrayList is empty
Iterator()Returns an iterator over the elements of the list
listIterator()Returns a list iterator over the elements of the ArrayList
E get(int index)Gets the element at the position passed as a parameter.
void ensureCapacity(int requiredCapacity)Ensures the minimum capacity of the ArrayList.
int lastIndexOf(Object o)Returns the index of the last occurrence of the element. If the element is not found, it returns -1.
Object[] toArray()Returns an array containing all of the elements in this list in the correct order.
Object clone()Allows cloning an ArrayList.
<T> T[] toArray(T[] a)Returns an array containing all the elements in the list in the correct order.
boolean contains(Object o)Returns TRUE if the object passed as a parameter exists
int indexOf(Object o)Returns the position or index of the object passed as a parameter.
E remove(int index)Removes the element at the position passed as a parameter.
boolean remove(Object o)Removes the first occurrence of the element passed as a parameter.
boolean removeAll(Collection<?> c)Removes all occurrences passed as a parameter.
boolean removeIf(Predicate<? super E> filter)Removes all elements that satisfy the predicate passed as a parameter.
protected void removeRange(int fromIndex, int toIndex)Removes the elements between a range passed as a parameter.
void replaceAll(UnaryOperator<E> operator)Replaces all elements of the list with the specified elements.
void retainAll(Collection<?> c)Retains all elements present in the collection passed as a parameter.
E set(int index, E element)Replaces the element passed as a parameter at the indicated position.
void sort(Comparator<? super E> c)Allows sorting the elements of the list based on the Comparator passed as a parameter.
Spliterator<E> spliterator()Allows creating a spliterator on the list.
int size()Returns the size of the list.
List<E> subList(int fromIndex, int toIndex)Returns a sublist between the values passed as parameters.
void trimToSize()Trims the capacity of this ArrayList instance to be the list’s current size.
Arraylist methods in Java

Examples of Usage of ArrayList in Java

Let’s see examples about main methods of ArrayList in Java.

Create an ArrayList

List<String> arraylist = new ArrayList(19);

Example of adding elements to an ArrayList in Java.

List listOfString = new ArrayList();
listOfString.add("hola");
listOfString.add("adios");

List auxListOfString = new ArrayList();
auxListOfString.addAll(listOfString);

Method to check if an element exists in an ArrayList in Java.

List listOfString = new ArrayList();
listOfString.add("hola");
boolean containsHola = listOfString.contains("hola");

Example removing an element in an ArrayList in Java

We will use remove to delete an element from the list. Remove returns true if the removal was successful.

List listOfString = new ArrayList<String>();
listOfString.add("hola");
boolean removed = listOfString.remove("hola");

Get size of an ArrayList

To get the size of an arrayList we are going to use size().

ArrayList<String> stringList = new ArrayList<String>();
  list.add("Hola");
  int totalSize = stringList.size();

Iterating over an ArrayList using Iterator

public static void main(String args[]){  
  ArrayList<String> stringList = new ArrayList<String>();
  list.add("Hola");
  list.add("Adios");    
  list.add("Hi");    
  Iterator itr=stringList.iterator();//getting the Iterator  
  while(itr.hasNext()){
   System.out.println(itr.next());
  }  
//también se puede hacer con lambda
  stringList.forEach(str->System.out.println(str));
 }  
}  

Sort an ArrayList in Java

Next, we are going to create a list of numbers and sort them by default using the sort method from smallest to largest:

List<Integer> numberList=new ArrayList<Integer>();  
  numberList.add(11);  
  numberList.add(500);  
  numberList.add(59);  
  numberList.add(10);  
  Collections.sort(numberList);  
  numberList.forEach(number->System.out.println(number));

Output:

10
11
59
500

Ways to iterate over an ArrayList in Java

Let’s see different ways to iterate over an ArrayList in Java. It’s important to note that how to iterate over an ArrayList in Java depends on whether the Java version is prior or posterior to Java 8:

Let’s see several ways to iterate over an ArrayList in Java:

  • Using an Iterator.
  • Iterating with forEach.
  • Using the ListIterator interface.
  • While loop.
  • Using forEachRemaining().
  • Using stream().
 public void iterateAnArrayList(){
    ArrayList<String> names=new ArrayList();
    names.add("Jose");
    names.add("Fran");
    names.add("Noel");
    names.add("Pablo");
    System.out.println("Con ListIterator");
    //Here, element iterates in reverse order
    ListIterator<String> namesIterator=names.listIterator(names.size());
    while(namesIterator.hasPrevious()) {
      String str=namesIterator.previous();
      System.out.println(str);
    }
    
    System.out.println("Con bucle For convencional:");
    for(int i=0;i<names.size();i++) {
      System.out.println(names.get(i));
    }
    System.out.println("Haciendo uso de ForEach");
    names.forEach(name->{ 
      System.out.println(name);
    });
    System.out.println("Con forEachRemaining():");
    Iterator<String> itr=names.iterator();
    itr.forEachRemaining(name-> System.out.println(name));
  
  
  System.out.println("Haciendo uso de stream()");
  names.stream().peek(name->System.out.println(name));
}

In the last case, where we used “peek” inside a stream. It is a recommended use for debugging purposes. Generally, we will use Map whenever we want to make a modification.

Example of retainAll() in an ArrayList

In this section we are going to see an example of using retainAll().

The retainAll() method is used to remove all elements that are not contained in the collection that is specifically passed or to keep all matching elements from the list passed as a parameter.

We can have the following exceptions:

  • ClassCastException: If the class of the elements being passed is incompatible.
  • NullPointerException: If the list contains any null element and the collection passed as a parameter does not allow it, or if the collection is null.

Let’s see an example of using retainAll() in Java:

class arrayListExamples{  
 public void retainAllExample(){  
    ArrayList<String> names=new ArrayList();
    names.add("Jose");
    names.add("Fran");
    names.add("Noel");
    names.add("Pablo");
    ArrayList<String> names2=new ArrayList();
    names2.add("Pepe");
    names2.add("Pablo");  
    names.retainAll(names2);  
    Iterator iter=al.iterator();  
      
   while(iter.hasNext()){  
      System.out.println(iter.next());  
   }  
 }  
}  

Output:

Pablo

What we have done with retainAll() in the previous example is to remove and keep from the first list the elements that are in the second list.

replaceAll in an ArrayList in Java

The replaceAll() method in an ArrayList is responsible for replacing each element of an ArrayList with the specified result passed as a parameter:

The syntax of the method would be as follows:

arraylist.replaceAll(UnaryOperator<E> operator)

Let’s see an example of an ArrayList in which we replace all the elements by adding one:

class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbersAddOne = new ArrayList<>();
        numbersAddOne.add(1);
        numbersAddOne.add(2);
        numbersAddOne.add(3);
        System.out.println("ArrayList: " + numbersAddOne);
        numbersAddOne.replaceAll(e -> e + 1);;
        System.out.println("ArrayList after add one: " + numbersAddOne);
    }
}

In this example, we create an ArrayList of integers called “numbersAddOne” and add three elements to it. Then, we print the original ArrayList to the console. Next, we use the replaceAll() method to replace each element in the ArrayList with the result of adding 1 to the element. Finally, we print the updated ArrayList to the console. The output will be:

ArrayList: [1, 2, 3]
ArrayList after add one: [2, 3, 4]

Big O Notation in ArrayList

When working with an ArrayList to retrieve an element from a list, it is important to consider the Big O Notation, that is, the complexity will depend on the way of access.

Depending on the operation with an ArrayList, its Big O Notation may change:

  • Accessing through index: If we access an element through its index, it will be O(1).
  • Insert or delete an element at the beginning. If we insert or delete an element at the beginning of a list, we have to shift all the remaining elements, so its complexity would be O(n), where n is the size of the list.
  • Inserting or deleting between beginning and end: Its Big O Notation would be O(n), as we have to traverse and shift elements.

Conclusion

In this post about the usage and main methods of ArrayList in Java, we have seen the main methods of ArrayList and their application. Knowing ArrayList well will prevent unnecessary problems or traversals in the structure, allowing us to optimize our application.

Leave a Reply

Your email address will not be published. Required fields are marked *