Java OCA OCP Practice Question 2535

Question

Consider the following program and predict the output:

import java.util.HashSet;

class Shape {
   public Shape(int r) {
      rollNo = r;/*from www.ja v a2  s  .  c  o  m*/
   }

   int rollNo;

   public int hashCode() {
      return rollNo;
   }
}

public class Main {
   public static void main(String[] args) {
      HashSet<Shape> students = new HashSet<>();
      students.add(new Shape(5));
      Shape s10 = new Shape(10);
      students.add(s10);
      System.out.println(students.contains(new Shape(10)));
      System.out.println(students.contains(s10));
   }
}
a)       false//from  w w w  .j av  a 2s . c o m
     true

b)      false
     false

c)       true
     false

d)      true
     true


a)

Note

Since, the newly created object is not part of the students set, the call to contains will result in false (note that the equals() method is not overridden in this class).

Object s10 is part of the students set.

So option a) is the correct answer.




PreviousNext

Related