Homework 06: Arrays and Lists

Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.


  1. (1 point) Write a method that computes the sum of the elements in an array of ints, with signature public int sum(int[] a).

  2. (1 point) Now, write a method that computes the sum of the elements in a List<Integer>, with signature public int sum(List<Integer> l). You may assume the List class has been imported.

  3. (2 points) Write a method public void insert(int x, int[] a) that inserts element x at the first cell in the array, moving everything else out of the way by shifting it “down” one element. The last element will just be dropped. For example, suppose you had an array a of ints of length 4 that contained the following values: [10, 2, 18, 0]. After a call of insert(42, a), the new contents of the array should be [42, 10, 2, 18].

  4. (1 point) How would you accomplish a similar task with a List<Integer> l? That is, what single line of code would let you insert an element at the start of the list l? (Unlike the array method above, this will not lose the last element of the list.)