ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class Version {
int major, minor;
Version(int ma, int mi) { major = ma; minor = mi; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Version v)) return false;
return major == v.major; // BUG: minor ignored
}
@Override
public int hashCode() { return Objects.hash(major, minor); }
}
// in main:
Set<Version> set = new HashSet<>();
set.add(new Version(1, 0));
set.add(new Version(1, 1));
System.out.println(set.size());- A. 1
- B. 2
- C. 0
- D. Non-deterministic
Correct answer: B. 2
hashCode() includes minor, so Version(1,0) and Version(1,1) hash to different buckets even though the buggy equals() (which ignores minor) would consider them equal — because they never land in the same bucket, equals() is never even invoked to compare them, so both get added: size 2, masking the equals bug entirely.
More OOP with C++ and Java questions
- What is printed? java public class Main { static int f() { int x = 10; try { return x; } finally { x = 20; } } public static void…
- What is printed? java public class Main { public static void main(String[] a) { try { System.out.print("A"); throw new RuntimeException()…
- Does this compile? java class MyException extends Exception {} class Demo { void risky() throws MyException { throw new MyException(); }…
- Does this compile? java class Demo { void risky() { throw new IllegalArgumentException(); } void call() { risky(); } }
- What is printed? java public class Main { public static void main(String[] a) { int[] arr = {1, 2, 3}; try { System.out.print(arr[5]); }…
- What is printed? java public class Main { static void a() { b(); } static void b() { c(); } static void c() { throw new…