Consider the following instance variable and method from a class. ArrayList name
ID: 3696184 • Letter: C
Question
Consider the following instance variable and method from a class. ArrayList nameList; public String getItem(int loc) { if(loc == nameList.size() – 1) return nameList.get(loc); else { String temp = getItem(loc+1); String thisOne = nameList.get(loc); if(temp.compareTo(thisOne) < 0) return temp; else return thisOne; } } Assume that nameList has been initialized as shown below. nameList --> | Harry | Chris | Barbara | Peter | John | Which of the following is returned by the call getitem(0)? Harry Chris Barbara Peter John
Explanation / Answer
Given function
public String getItem(int loc)
{
if(loc == nameList.size() – 1) //loc=0,nameList.size()-1=4
return nameList.get(loc);
else
{
String temp = getItem(loc+1);// this recursive function sets temp="john"
String thisOne = nameList.get(loc);
if(temp.compareTo(thisOne) < 0) //this condition is becomes false as this function returns the value 2
return temp;
else
return thisOne;
}
}
So the string returned by function getitem(0) is Harry.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.