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

Q) Answer the following questions regarding the ArrayList<> class [Answer for a,

ID: 3574139 • Letter: Q

Question

Q) Answer the following questions regarding the ArrayList<> class [Answer for a, c, d]

(a) Find all the methods named remove() in ArrayList<> class
Answer: ???

(b) Execute the following program and submit the output.

import java.util.ArrayList;
public class TestAL {
public static void main(String [] args) {
ArrayList<Object> al = new ArrayList<Object>();
al.add(3);
al.add(4);
al.add(new Integer(5));
for(Object x: al) {
System.out.println(x);
}
}
}

Answer:
3
4
5

(c) Explain the type of x for the above program
Answer: ????


(d) Excute this program and then, explain the reason of the error.
import java.util.ArrayList;
public class RemoveIndex {
   public static void main(String [] args) {
       ArrayList<Object> al = new ArrayList<Object>();
       al.add(3);
       al.add(4);
       al.add(5);
       al.remove(3);
       System.out.println(al);
       }
       }

Answer: ???

Explanation / Answer

a) Find all the methods named remove() in ArrayList<> class
remove(int index) - It remove the element available at the index.
remove(Object o) -It removes the very first occurence of the Object o.

c)Explain the type of x for the above program
x has a type of Object basically used in the program to traverse the ArrayList containing objects.
  
(d) Excute this program and then, explain the reason of the error.
import java.util.ArrayList;
public class RemoveIndex {
public static void main(String [] args) {
ArrayList<Object> al = new ArrayList<Object>();
al.add(3);
al.add(4);
al.add(5);
al.remove(3);
System.out.println(al);
}
}

Error:
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3   
at java.util.ArrayList.rangeCheck(ArrayList.java:653)   
at java.util.ArrayList.remove(ArrayList.java:492)

Reason: We are facing this error as we have called al.remove(3) i.e remove the element present at index=3,but we had added only 3 set of objects i.e index=0,1 and 2 so the code is not able to find the index 3.


Note:Please do ask in case of any doubt,would glad to help you,Thanks !!