0

Consider the following method hat is intended to modify its parameter nameList by replacing all occurrences of name with newValue

public void replace(ArrayList<String> nameList, String name, String newValue) {

    for (int j = 0; j < nameList.size(); j++) {

        if (/*expression*/)
            namelist.set(j, newValue);

    }
}

Which of the following can be used to replace /* expression */ so that replace will work as intended?

(a) nameList.get(j).equals(name)
(b) ...
(c) ...
(d) ...
(e) nameList[j].equals(name)

I chose e, but the correct answer is a. I don't quite understand why a works but not e, and I'm not entirely sure what the difference is between the two...

You can find the question here, on page 9:
http://xhs-java-oop.wikispaces.com/file/view/PracticeProblems.pdf

demongolem
  • 9,474
  • 36
  • 90
  • 105
  • (e) would not compile because nameList is not an array type. But even with (a) the code would not compile because namelist.set(j, newValue) refers to namelist instead of nameList (nitpicking but i guess its an exam question) – salyh May 03 '14 at 17:54
  • @salyh looking at the original exam it appears that that was just a typo by the poster – awksp May 03 '14 at 18:01

1 Answers1

2

You are given an ArrayList, which does not function like a plain old array. An ArrayList gives the method .get(int i) to return the element at index i.

This is because an ArrayList is a class, with methods and fields, rather than a primitive data type.

Aarowaim
  • 801
  • 4
  • 10