In: Computer Science
Create a static method with the appropriate inputs and outputs. Call each of them in the main method.
Write a method called removeAllInstances() which takes in a List and item4 . The method then proceeds to remove each item in the list that matches the given item. For example, if the method is passed the List [1, 4, 5, 6, 5, 5, 2] and the Integer 5, the method removes all 5’s from the List. The List then becomes [1, 4, 6, 2]. It should return nothing, since the changes the List it was provided. 5
Please do this in Java.
ANSWER:-
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
class GFG
{
public static void
removeAllInstances(List<Integer>l,int r)
{
Iterator itr = l.iterator(); //
iterator use for list treverse
while (itr.hasNext())
{
int x = (Integer)itr.next();
if (x==r)
itr.remove();
}
}
public static void main(String[] args)
{
int num;
Scanner sc=new Scanner(System.in); // scanner use for
user input
System.out.println("how many number you want to enter
: ");
int n=sc.nextInt();
List<Integer>l = new ArrayList<Integer>(); // create a
list
System.out.println("Enter a numbers : ");
for(int i=0;i<n;i++)
{
num=sc.nextInt();
l.add(num);
}
System.out.println("enter a number for remove : ");
int r=sc.nextInt();
System.out.println("Original list : "+l);
removeAllInstances(l,r);
System.out.println("Modified ArrayList : "+ l);
}
}
OUTPUT:-
// If any doubt please comment