1Z0-803 · Question #210
Given: Which code fragment, when inserted at line 14, enables the code to print Mike Found?
The correct answer is D. int f = ps.indexOf(p2);. To enable the code to print 'Mike Found', the indexOf method must be called with an object reference that is present in the ps list.
Question
Given:
Which code fragment, when inserted at line 14, enables the code to print Mike Found?
Exhibit
Options
- Aint f = ps.indexOf {new patient ("Mike")};
- Bint f = ps.indexOf (patient("Mike"));
- Cpatient p = new Patient ("Mike");
- Dint f = ps.indexOf(p2);
How the community answered
(31 responses)- A10% (3)
- B3% (1)
- C19% (6)
- D68% (21)
Why each option
To enable the code to print 'Mike Found', the `indexOf` method must be called with an object reference that is present in the `ps` list.
This fragment contains a syntax error (`{{ }}`) and, even if corrected to `new Patient("Mike")`, it would create a new object instance. Without `equals()` overridden in `Patient` to compare content, `indexOf` would likely return -1 as it compares object references.
This fragment contains a syntax error (`patient("Mike")` instead of `new Patient("Mike")`). Even if fixed, it would create a new object instance, which typically would not be found by reference comparison if `equals()` is not overridden.
This fragment only creates a new `Patient` object `p` but does not perform an `indexOf` operation on the `ps` list or assign a value to a variable `f`, so it does not directly enable the desired print statement.
The `indexOf` method in Java's `List` interface, when called with an object `p2`, checks for object identity (using `==`) unless the `equals` method is overridden. If `p2` refers to an existing `Patient` object already added to the `ps` list, `indexOf(p2)` will correctly return its index, enabling the 'Mike Found' message.
Concept tested: Java List.indexOf method, object identity
Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html#indexOf(java.lang.Object)
Topics
Community Discussion
No community discussion yet for this question.
