Java. Class ArrayList. Methods that change data in the array

Class ArrayList. Methods that change data in the array


Contents


Search other resources:

 
1. Method add(). Add element to the end of array

The add() method adds an element to the array. The method has two overloaded implementations

add(E obj)
add(int index, E obj)

here

  • E – type of array elements;
  • obj – object (element) added to the array;
  • index is the position where the obj element should be inserted into the array.

Example. The example forms an array of squares of numbers from 1 to 10. The add() method is used to add a number to the end of the array.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method add() - add an element to the end of an array
    // 1. Create an array of integers
    ArrayList<Integer> AI = new ArrayList();

    // 2. Add squares of numbers from 1 to 10 to the array
    for (int i=1; i<=10; i++)
      AI.add(i*i);

    // 3. Display the array
    System.out.println(AI);

    // 4. Add the number 555 to the beginning of the array at position 0
    AI.add(0, 555);
    System.out.println(AI);
  }
}

Program result

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[555, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

2. Method addAll(). Append collection to array

The addAll() method is designed to add an already existing collection to an array. A collection can be a collection, a queue, another array, and so on. The method has two overloaded implementations

addAll(Collection<? extends E>)
addAll(int index, Collection<? extends E>)

here

  • E – type of array (collection) elements;
  • index – the position from which the insertion occurs.

Example. Demonstrates the use of the addAll() method for an array of integers.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method addAll() - add a collection to the array
    // 1. Create an array of 5 numbers of type Float
    ArrayList<Float> AI = new ArrayList();
    AI.add(1.0f);
    AI.add(2.0f);
    AI.add(3.0f);
    AI.add(4.0f);
    AI.add(5.0f);
    System.out.println("AI = " + AI);

    // 2. Create another array of 3 numbers of type Float
    ArrayList<Float> AI2 = new ArrayList();
    for (int i=1; i<=3; i++)
      AI2.add(i*15f);
    System.out.println("AI2 = " + AI2);

    // 3. Add array AI2 to the end of array AI
    AI.addAll(AI2);
    System.out.println("AI + AI2 = " + AI);

    // 4. Write AI2 array to AI array starting from position 2
    AI.addAll(2, AI2);
    System.out.println("AI[2] + AI2 = " + AI);
  }
}

Program result

AI = [1.0, 2.0, 3.0, 4.0, 5.0]
AI2 = [15.0, 30.0, 45.0]
AI + AI2 = [1.0, 2.0, 3.0, 4.0, 5.0, 15.0, 30.0, 45.0]
AI[2] + AI2 = [1.0, 2.0, 15.0, 30.0, 45.0, 3.0, 4.0, 5.0, 15.0, 30.0, 45.0]

 

3. Method clear(). Clear the array

The clear() method is for clearing an array. According to the documentation, the general form of a method declaration is as follows

public void clear();

 

Example. The example creates a collection of delimiter characters.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // The clear() method - clear the collection
    // 1. Create a collection of delimiters in a sentence
    ArrayList<Character> AL = new ArrayList();
    AL.add(';');
    AL.add(':');
    AL.add(',');
    AL.add('.');
    AL.add('!');
    AL.add('?');
    AL.add(' ');

    // 2. Display the collection
    System.out.println("AL => " + AL);

    // 3. Clear the collection
    AL.clear();

    // 4. Print the collection after cleaning
    System.out.println("AL.clear() => " + AL);
  }
}

Program result

AL => [;, :, ,, ., !, ?,  ]
AL.clear() => []

 

4. Method remove().Delete the element at the specified position

The remove() method can be used to remove an element at a given position. According to the documentation, the method declaration is as follows

public E remove(int index);

here

  • E – type of array (collection) elements;
  • index – number of the position to be deleted. The position is numbered from 0.

The method returns the value of the element to be removed from the array (collection).

If the index value is out of range

(index < 0 || index >= size())

then an IndexOutOfBoundsException will be thrown.

Example.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method remove() - remove a single element from an array
    // 1. Create a collection of real numbers
    ArrayList<Float> AL = new ArrayList<Float>();
    AL.add(2.8f);
    AL.add(3.5f);
    AL.add(7.2f);
    AL.add(9.4f);
    AL.add(5.2f);

    // 2. Pring the collection
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();

    // 3. Remove element at position 2 which has value 7.2
    AL.remove(2);

    // 4. Display modified collection
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
  }
}

Program result

AL => 2.8  3.5  7.2  9.4  5.2
AL => 2.8  3.5  9.4  5.2

 

5. Method removeAll().Delete a group of elements from a collection

With the removeAll() method, you can remove multiple elements represented as a collection. According to the documentation, the method declaration is as follows:

public boolean removeAll(Collection<?> c);

here

  • c – collection (array) of elements to be removed from the current collection.

The method returns true if the current array has changed as a result of the call.

Example.

The example creates two integer collections:

  • AL – the original collection of numbers;
  • AL2 – a collection of numbers to be removed from the AL collection.

The removeAll() method removes all parts from the AL2 collection from the AL collection.

 

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method removeAll() - remove a group of elements from an array
    // 1. Create a collection of integers
    ArrayList<Integer> AL = new ArrayList<Integer>();
    AL.add(2);
    AL.add(3);
    AL.add(2);
    AL.add(4);
    AL.add(7);
    AL.add(3);
    AL.add(4);
    AL.add(5);
    AL.add(6);
    AL.add(1);

    // 2. Display the original collection
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();

    // 3. Create a collection of numbers to be removed
    ArrayList<Integer> AL2 = new ArrayList<Integer>();

    // delete all numbers 2, 4, 7
    AL2.add(2);
    AL2.add(4);
    AL2.add(7);

    // 4. Call the removeAll() method
    AL.removeAll(AL2);

    // 4. Display modified collection
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
  }
}

Program result

AL => 2  3  2  4  7  3  4  5  6  1
AL => 3  3  5  6  1

 

6. Method removeIf(). Modify collection based on predicate

With the removeIf() method, you can remove elements from a collection according to a condition. As a result, a new collection (array) is formed. The general form of a method declaration is as follows

public boolean removeIf(Predicate<? super E> filter);

here

  • filter – reference (predicate) that defines the filtering condition. The condition is specified by a lambda expression.

The method returns true if at least one element has been removed.

Example.

The example demonstrates the execution of the removeIf() method. The following operations are shown:

  • a collection of integers is created;
  • a predicate is formed in which numbers greater than 4 are determined;
  • the removeIf() method is called, with the help of which a new array of numbers is formed according to the predicate.

 

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method removeIf() - change an array according to a given condition
    // 1. Create a collection of integers
    ArrayList<Integer> AL = new ArrayList<Integer>();
    AL.add(2);
    AL.add(3);
    AL.add(2);
    AL.add(4);
    AL.add(7);
    AL.add(3);
    AL.add(4);
    AL.add(5);
    AL.add(6);
    AL.add(1);

    // 2. Display the original collection
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();

    // 3. Declare a reference to the Predicate<Integer> interface
    Predicate<Integer> ref;

    // 4. Form a condition for a ref link based on a lambda expression:
    //    take all numbers greater than 4
    ref = (value) -> value > 4;

    // 5. Call the removeIf() method and pass it a ref as a condition
    AL.removeIf(ref);    // delete all numbers that are greater than 4

    // 6. Output modified array AL
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();
  }
}

Program result

AL => 2  3  2  4  7  3  4  5  6  1
AL => 2  3  2  4  3  4  1

 

7. Method replaceAll(). Perform calculations on each element of the array

Using the replaceAll() method, you can apply some operation to each element of an array. Such an operation can be, for example, the product of each element by 2. According to the documentation, the general form of a method declaration is as follows:

public void replaceAll(UnaryOperator<E> operator);

here

  • operator – a lambda expression that defines an operation on each element of the sequence. The lambda expression is formed using the UnaryOperator<T> functional interface.

Example. The example creates an array of integers. Then each element of the array is multiplied by 3 using the replaceAll() method. To perform the calculation, a reference to the appropriate lambda expression is generated.

 

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method replaceAll() - change the value of the elements of the original array
    // 1. Create a collection of integers
    ArrayList<Integer> AL = new ArrayList<Integer>();
    AL.add(2);
    AL.add(3);
    AL.add(2);
    AL.add(4);
    AL.add(7);
    AL.add(3);

    // 2. Retrieve a collection using an iterator
    Iterator<Integer> it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext())
      System.out.print(it.next()+"  ");
    System.out.println();

    // 3. Form a lambda expression that multiplies an element by 3
    UnaryOperator<Integer> op = (num) -> num*3;

    // 4. Call the replaceAll() method and apply the op operator to it
    AL.replaceAll(op);

    // 5. Output the modified collection (array) of integers
    it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext()) {
      System.out.print(it.next() + "  ");
    }
  }
}

Program result

AL => 2  3  2  4  7  3
AL => 6  9  6  12  21  9

 

8. Method set(). Set new value in element

The set() method sets a new value at the given array position. In other words, the old array value at the given position is replaced by the new one.

The method declaration has the form

public E set(int index, E element);

here

  • index – insertion position (numbered from 0);
  • element – the new value to be set at position index.

The method returns the previous value set at the given position.

If the value of index is out of range, i.e.

(index < 0 || index >= size())

then an IndexOutOfBoundsException will be thrown.

Example.

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method set() - set a value in an individual array element
    // 1. Create a collection of strings
    ArrayList<String> AL = new ArrayList<String>();
    AL.add("a");
    AL.add("b");
    AL.add("c");

    // 2. Print the original array using an iterator
    Iterator<String> it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext())
      System.out.print(it.next()+"  ");
    System.out.println();

    // 3. Set new value at element at index 1
    String oldValue;
    oldValue = AL.set(1, "bbb");

    // 4. Print the previous string
    System.out.println("oldValue = " + oldValue);

    // 5. Output modified array
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();
  }
}

Program result

AL => a  b  c
oldValue = b
AL => a  bbb  c

 

9. Method sort(). Sort array elements

You can sort the elements of an array using the sort() method. The general form of a method declaration is as follows

public void sort(Comparator<? super E> c);

here

  • c is a comparator (condition) that implements the principle of comparing any two array elements. The comparator is used in the case of developing your own class, the objects of which can be sorted according to some criterion. In this case, the class must implement the Comparator interface. This interface defines a compare() method that compares two elements. Specifically, this method needs to be redefined and implemented in this class and set its own comparison mechanism.

For standard wrapper types (Integer, Double, String, etc.), an internal comparator is implemented that sorts elements in natural order (from smallest to largest or alphabetically).

To use the standard sort method, call the sort() method with a null argument

AL.sort(null);

where AL is an array of elements to be sorted.

Example.

 

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Method sort() - sort in natural order
    // 1. Create array of strings
    ArrayList<String> AL = new ArrayList<String>();
    AL.add("jklm");
    AL.add("abcd");
    AL.add("elsd");
    AL.add("lkls");
    AL.add("azsd");

    // 2. Print the original array
    Iterator<String> it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext())
      System.out.print(it.next()+"  ");
    System.out.println();

    // 3. Sort array elements, sort() method
    AL.sort(null);

    // 4. Print sorted array
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();
  }
}

Program result

AL => jklm  abcd  elsd  lkls  azsd
AL => abcd  azsd  elsd  jklm  lkls

 


Related topics