14: Static Method Finger Exercises
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.
(Get ready to move your fingers! Remember, you can use Eclipse to check that you’re doing these right!)
A. (2 points) Suppose you have a List<E>
. Write a generic static method reverse
that modifies the list in-place, reversing the order of all elements that the list contains. (Remember: the syntax for generic static methods: the type parameter goes before the return type, so the declaration will start with something like public static <E> void reverse(List<E> list)
.)
For example, after reverse
the list [1, 2, 3, 4, 5]
would be changed to [5, 4, 3, 2, 1]
.
B. (2 points) Write a generic static method groupUp
that takes in an int
parameter and a List<E>
parameter, and returns a List<List<E>>
.
In particular, the method should group up the elements of the Listint
parameter.
Edge cases: If the int
parameter is less than 1 or greater than the size of the input list, you should return null
For example:
- If the input is the list
[1, 2, 3, 4, 5]
and theint
is 1, the output would be the list of 5 lists[[1], [2], [3], [4], [5]]
. - If the input is the list
[1, 2, 3, 4, 5]
and theint
is 2, the output would be the list of 4 lists[[1, 2], [2, 3], [3, 4], [4, 5]]
. - If the input is the list
[1, 2, 3, 4, 5]
and theint
is 4, the output would be the list of 2 lists[[1, 2, 3, 4], [2, 3, 4, 5]}
. - If the input is the list
[1, 2, 3, 4, 5]
and theint
is 5, the output would be the list of 1 lists[[1, 2, 3, 4, 5]]
.