In: Computer Science
Determine the outputs of the code:
String[]array=
{"Namath","Sauer","Namath","Namath","Snell","Snell","Namath","Namath","Namath",
"Maynard","Namath","Namath"};
ArrayList<String>list=new
ArrayList<String>();
for(int
i=0;i<array.length;i++)
{
list.add(array[i]);
}
System.out.println("OUTPUT
1");
System.out.println(list);
System.out.println("OUTPUT
2");
for(int
i=0;i<list.size();i++)
{
if(list.get(i).equals("Namath"))
{
System.out.println(i+"\t"+
list.remove(i));
}
}
System.out.println("OUTPUT
3");
for(String s:list)
{
System.out.println(s);
}
/*
OUTPUT 1
OUTPUT 2
OUTPUT 3
*/
ANSWER: Here I am giving you the code and output. The explanation is given in the code as a comment.
CODE:
import java.util.*;
public class Main
{
public static void main(String[] args) {
String[]array=
{"Namath","Sauer","Namath","Namath","Snell","Snell","Namath","Namath","Namath",
"Maynard","Namath","Namath"};
ArrayList<String>list=new ArrayList<String>();
for(int i=0;i<array.length;i++)
{
list.add(array[i]);
}
System.out.println("OUTPUT 1");// In output here its simply
printing the list items
System.out.println(list);
System.out.println("OUTPUT 2");// In output2 if the list items is
equal to the Namath then it is removing it from the list and
printing at which index it is available.
for(int i=0;i<list.size();i++)
{
if(list.get(i).equals("Namath"))
{
System.out.println(i+"\t"+ list.remove(i));
}
}
System.out.println("OUTPUT 3"); // In this OUTPUT3 remaining list
items will be printed after removing Namath.
for(String s:list)
{
System.out.println(s);
}
}
}
OUTPUT: