?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Difficult

Removing Elements from Array and Creating New Resized Array

APCSA-TVLVJC

Assume that the fishes array is full of fish types. The for loop below loops through the fishes array and removes all elements that have types that contain the word "fish".

Which removeFish method will remove the correct elements and shrink the length of the returned array by the number of elements removed?

For example, if the fishes array contains "tuna", "swordfish" and "catfish" with a length of 3, the resulting fishes array should only contain "tuna" with a length of 1.

for (int i=0; i<fishes.length; i++)
{
    if (fishes[i].indexOf("fish")>=0)
    {
        fishes = removeFish(fishes, i);
        i--;
    }
}
A
// Parameters: fishes array, k = index of element to be removed
// Prerequisite: fishes has at least one element.
public static String[] removeFish(String[] fishes, int k)
{
    String[] temp = new String[fishes.length-1];
    int j=0;
    for (int i=0; i<fishes.length; i++)
    {
        if (i != k)
        {    
            temp[j] = fishes[i];
        }
        j++;
    }
    return temp;
}
B
// Parameters: fishes array, k = index of element to be removed
// Prerequisite: fishes has at least one element.
public static String[] removeFish(String[] fishes, int k)
{
    String[] temp = new String[fishes.length-1];
    int j=0;
    for (int i=0; i<fishes.length; i++)
    {
        if (i != k)
        {    
            temp[j] = fishes[i];
            j++;
        }
    }
    return temp;
}
C
// Parameters: fishes array, k = index of element to be removed
// Prerequisite: fishes has at least one element.
public static String[] removeFish(String[] fishes, int k)
{
    if (fishes.length==1 && k==0)
        return new String[0];
    String[] temp = new String[fishes.length-1];
    int j=0;
    for (int i=0; i<fishes.length; i++)
    {
        if (i != k)
        {    
            temp[j] = fishes[i];
        }
        j++;
    }
    return temp;
}
D
// Parameters: fishes array, k = index of element to be removed
// Prerequisite: fishes has at least one element.
public static String[] removeFish(String[] fishes, int k)
{
    if (fishes.length==1 && k==0)
        return new String[0];
    String[] temp = new String[fishes.length-1];
    for (int i=0; i<fishes.length; i++)
    {
        if (i != k)
        {    
            temp[i] = fishes[i];
        }
    }
    return temp;
}
E
// Parameters: fishes array, k = index of element to be removed
// Prerequisite: fishes has at least one element.
public static String[] removeFish(String[] fishes, int k)
{
    String[] temp = new String[fishes.length-1];
    for (int i=0; i<fishes.length; i++)
    {
        if (i != k)
        {    
            temp[i] = fishes[i];
        }
    }
    return temp;
}