223k views
0 votes
Which of these methods will properly traverse two ArrayLists and print any index that have the same value in both ArrayLists?

A) public void printSharedValues(ArrayList array1, ArrayList array2)
{
int index = 0;
while(index < array1.size())
{
if(array1.get(index) == array2.get(index))
{
System.out.println(index);
}
index++;
}
}

B) public void printSharedValues(ArrayList array1, ArrayList array2)
{
int index = 0;
while(index < array1.size())
{
if(array1.get(index) == array2.get(index))
{
System.out.println(index);
}
index--;
}
}

C) public void printSharedValues(ArrayList array1, ArrayList array2)
{
int index = 0;
int size;
if(array1.size() > array2.size())
{
size = array2.size();
}
else
{
size = array1.size();
}
while(index < size)
{
if(array1.get(index) == array2.get(index))
{
System.out.println(index);
}
index++;
}
}

D) public void printSharedValues(ArrayList array1, ArrayList array2)
{
int size;
if(array1.size() > array2.size())
{
size = array2.size();
}
else
{
size = array1.size();
}
while(index < size)
{
int index = 0;
if(array1.get(index) == array2.get(index))
{
System.out.println(index);
}
index++;
}
}

User Psergiocf
by
8.5k points

1 Answer

0 votes

Final answer:

The correct way to identify shared indexes in two ArrayLists is represented by method C, which accounts for different list sizes and properly increments the index within a while loop.

Step-by-step explanation:

The correct method to traverse two ArrayLists and print any index that have the same value in both ArrayLists is option C. This method first determines the smaller size of the two lists to avoid IndexOutOfBoundsException, and then iterates through both lists using a while loop. If the values at the current index in both lists are the same, it prints the index. Moreover, it uses index++ to properly increment the index variable after each iteration, ensuring the loop progresses correctly through the lists.

User Jihun No
by
7.7k points