ProgrammingHardProduct-company interview pattern
This class is meant to be immutable. What change is still needed?
This class is meant to be immutable. What change is still needed?
public final class Team {
private final List<String> members;
public Team(List<String> m) { members = m; }
public List<String> getMembers() { return members; }
}- A. Nothing; final class plus private final fields make it immutable
- B. Copy the list in the constructor and return an unmodifiable view or copy from the getter
- C. Make the getter method final
- D. Mark members as static
Correct answer: B. Copy the list in the constructor and return an unmodifiable view or copy from the getter
final stops reassignment of the field, not changes to the list. The caller still holds the list passed in, and getMembers() exposes the internal list, so either side can change it. Defensive copies (e.g. List.copyOf(m)) fix both leaks.
More OOP with C++ and Java questions
- What is printed? cpp struct V { int x; V(int a) : x(a) {} V operator+(const V& o) const { return V(x + o.x 2); } }; int main() { V a(1)…
- What is printed? java class A { void m(A a) { System.out.print("AA"); } } class B extends A { void m(A a) { System.out.print("BA"); } void…
- Class P is in package a and declares protected int x. Class C is in package b and extends P. Inside an instance method of C, which of…
- What happens when this Java class is compiled? java class Util { static void f(List<String> l) { } static void f(List<Integer> l) { } }
- How many of the following statements about equals() and hashCode() in Java are correct? (i) If a.equals(b) is true, a.hashCode() must…
- On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print? cpp class P { int id; public…