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

I need help with this section. 3.1 Write code that creates an ArrayList<Integer>

ID: 3734140 • Letter: I

Question

I need help with this section.

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):

0123401234

I've written this code already for 3.1 but I need help writing the code for the following sections so I can see how they work...

import java.util.ArrayList;

public class HW1 {

    public static void main(String[] args) {

        ArrayList list = new ArrayList();

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

            for (int j = 0; j < 5; ++j) {

                list.add(j);      } }

        System.out.print(list); } }

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?

}

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

Hi, I have answered first 3 Questions.

Please repost others in separate post.

1)

import java.util.*;

import java.util.Arrays;

public class Test1 {

  

   public static void main(String[] args) {

      

       List<Integer> list = Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 4, 3, 2, 1, 0});

      

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

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

       }

      

       System.out.println(list);

   }

}

2)

Ans: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]

3)

int count = 0;

       for(int x : list) {

           if(x < 0)

               count++;

       }

      

       System.out.println(count);