Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Alisber Ainan Using the JCF List interface and ArrayList class, write a java pro

ID: 3917248 • Letter: A

Question

Alisber Ainan Using the JCF List interface and ArrayList class, write a java program having only main method. Create an object list of type ArrayList to store Strings. Ask the user to enter 10 Strings and add these Strings to the list object. Input the Strings using class Scanner Output the contents of the list of strings with their indices. Assume that the index of the first element is O. Next, the user will enter two elements that should be swapped. If both elements are found in the list, swap these two elements in the list and output modified list, else output an error message. Public static main

Explanation / Answer

import java.util.*;  

public class Array_list{  

public static void main(String args[]){  

ArrayList<String> list=new ArrayList<String>();

Scanner input=new Scanner(System.in);

System.out.println("Enter 10 strings");

String str1=new String();

for(int i=0;i<10;i++){

str1=input.next();

list.add(str1);

}

int i=0;

Iterator itr=list.iterator();

while(itr.hasNext()){  

System.out.println("element at index "+ i +" is : "+ itr.next());

i++;

}  

System.out.println("Enter two string");

String str2=new String();

str1=input.next();

str2=input.next();

int index1=list.indexOf(str1);

int index2=list.indexOf(str2);

if(index1==-1||index2==-1)System.out.println("one of string not found in list");

else {

Collections.swap(list, index1, index2);

System.out.println("list after swap ");

itr=list.iterator();

i=0;

while(itr.hasNext()){  

System.out.println("element at index "+ i +" is : "+ itr.next());

i++;

}  

}

}  

}  

for any query please comment.

please upvote if find it helpful.

Thank you.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote