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

3 ArrayLists 3.1 Write code that creates an ArrayList<Integer> object named list

ID: 2246992 • Letter: 3

Question

3 ArrayLists

3.1 Write code that creates an ArrayList<Integer> object named list and fills list with these numbers (using one or a pair

of for or while loops):

0 1 2 3 4 0 1 2 3 4

3.2 Consider the ArrayList<Integer> object named list containing these Integers:

list = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 }

What are the contents of list after this loop completes?

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

list.set(i, list.get(i) + list.get(i-1));

}

3.3 Write an enhanced for loop that counts how many numbers in an ArrayList<Integer> object named list are negative.

Print the count after the loop terminates.

3.4 Write a method named arrayListSum() that has one parameter pList which is an object of the class ArrayList

<Integer>. The method shall return the sum of the elements of pList.

3.5 Write a method named named arrayListCreate() that has two int parameters pLen and pInitValue. The method shall

create and return a new ArrayList<Integer> object which has exactly pLen elements. Each element shall be initialized

to pInitValue.

3.6 Write a void method named insertName() that has two input parameters: (1) pList which is an object of ArrayList

<String> where each element of pList is a person's name; and (2) a String object named pName. Assume the names in

pList are sorted into ascending order. The method shall insert pName into pList such that the sort order is maintained.

3.7 Write a void method named arrayListRemove() which has two parameters: pList is an object of the ArrayList

<Integer> class and pValue is an int. The method shall remove all elements from pList that are equal to pValue.

-------------------------------------------------------------------

Explanation / Answer

Answer for 3.1: This is the coding for array list using one or pair of for or while loops

ArrayList<Integer> list=new ArrayList<Integer>(10); //creating an an object

for(int i=0;i<5;++i)

{             // perform iteration

list.add(i); //adding elements to list

}

for(int i=0;i<5;++i)

{

list.add(i); //adding elements to list

}

When we write above code in c language:

#include<stdio.h>

#include<conio.h>

main(){

int i,a[10];

for(i=0;i<5;++i){

printf(“%d”,i);}

for(i=0;i<5;++i){

printf(“%d”,i);}

getch();}

Answer for 3.4 question: this is actual part of coding

public int arrayListSum(ArrayList<Integer>plist) //method with access modifier public(access any where)

{

int sum=0; //initialization

for(int i=0;i<plist.size();i++){

sum +=plist.get(i); //getting list of elements and performing sum

}

return sum; //moving back to sum for perform operation until satisfy the condition