Remove an Element from arraylist in Java

Remove an element from arraylist in java. Delete the specified integer from an array with a Java program. Enter the array’s size, followed by all of the array’s elements. Now type in the element you wish to get rid of. We locate the element’s location first, then shift the positions of all the elements after the element to be deleted is removed one by one. the Java source code for the Delete the Specified Integer from an Array program.

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, x, flag = 1, loc = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the numbers that you want in array");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the element you want to delete");
x = s.nextInt();
for (int i = 0; i < n; i++)
{
if(a[i] == x)
{
flag =1;
loc = i;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
for(int i = loc+1; i < n; i++)
{
a[i-1] = a[i];
}
System.out.print("After deleting the numbers");
for (int i = 0; i < n-2; i++)
{
System.out.print(a[i]+",");
}
System.out.print(a[n-2]);
}
else
{
System.out.println("Element not found");
}
}
}

 

Output:

Enter the numbers that you want in array 5
Enter all the elements
34
56
78
89
12
Enter the element you want to delete56
After deleting the numbers34,78,89,12

ArrayList in Java Program

The ArrayList class, which may be found in the java.util package, is a resizable array. The distinction between a built-in array and an ArrayList in Java is that an array’s size cannot be changed.

Flag Variable to Execute Remove an Element From arraylist in Java

A flag variable is a variable that you create to have one value until a condition is true or false, at which point the variable’s value is changed. It is a variable that can be used to regulate the execution of a function or statement, allowing you to check for specific conditions while your function is running. 

A flag is a value in computer science that serves as a signal for a function or process. The flag’s value is used to determine the next step in a program. Flags are frequently binary flags with a boolean value.

Break Statement in Java

The Java break command terminates a loop’s execution. After the loop, the interpreter goes on to the next statement in the program. If you want your loop to stop executing if a given condition is met, use the break statement. Using this program we can run to remove an element from arraylist in java