Task 1
ArrayList implements the add(int index, E element) method. We cannot use this method if we are using
a traditional array. In this task, you are to modify the file Homework05_Task1.java below, and finish
writing the insertDouble(double[] array, int index, double element) method so that it properly inserts an
element in the array. You should make sure that the index is valid.
Example:
double[] a = {1, 2, 3, 4, 5};
a = insertDouble(a, 0, 0.5);
// a = {0.5, 1, 2, 3, 4, 5};
Homework05_Task1.java
/*
* Homework05_Task1.java
* Finish implementing the insertDouble(double[] array, int index, double element)
* method so that it properly inserts an element in the array.
*/
public class Homework05_Task1 {
/**
* insertDouble
* Inserts an element into the given array the given index.
*/
public static double[] insertDouble(double[] array, int index, double element) {
double[] result = new double[array.length];
// YOUR CODE HERE
return result;
}
public static void main(String[] args) {
double[] a = {1, 2, 3, 4, 5, 6, 7, 9, 10};
a = insertDouble(a, 7, 8);
for (double e : a) {
System.out.printf("%.0f\n", e);
}
}
}
Task 2
ArrayList also allows us to easily remove elements. In this task, modify the remove(double[] array, int
index) method in the file Homework05_Task2.java below, so that the program properly removes an
element from the list. You should make sure that the index is valid.
Example:
double[] a = {1, 2, 3, 4, 5};
a = remove(a, 2);
// a = {1, 2, 4, 5};
Homework05_Task2.java
/*
* Homework05_Task2.java
* Complete the remove(double[] array, int index) method so that the program
* properly removes an element from the list.
*/
public class Homework05_Task2 {
/*
* remove
* Removes the element at the specified index from the list.
*/
public static double[] remove(double[] array, int index) {
double[] result = new double[array.length];
// YOUR CODE HERE
return result;
}
public static void main(String[] args) {
double[] a = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
a = remove(a, 4);
for (double e : a) {
System.out.printf("%.0f\n", e);
}
}
}
Task 3
Create a method findElement(double[] array, double element) that searches through the given array in
order to determine if the given element exist. You should make sure that the index is valid.
Example:
double[] a = {1, 2, 3, 4, 5};
int index = findElement(a, 3);
// index = 2
Task 4
Create a method setElement(double[] array, int index, double element) which changes the element at
the given index in the array. You should make sure that the index is valid.
Example:
double[] a = {1, 2, 3, 4, 5};
setElement(a, 1, 10);
// a[1] = 10
Purchase answer to see full
attachment