What will be printed after execution of this code?

class User {
	private String name;
	public User( String name ) {
		this.name = name;

	public boolean equals( Object obj ) {
		User user = (User) obj;
		return user.name.equals( name );

	public String toString() {
		return name;

class Foo {
	public static void main(String...arguments) {  //1
		User user1 = new User( "John" ); 
		User user2 = new User( "Bill" ); 
		User user3 = new User( "John" ); 

		Set<User> userSet = new HashSet<User>();
		userSet.add( user1 );
		userSet.add( user2 );
		userSet.add( user3 );  //2

		System.out.println( "Count of users: " + userSet.size() );  //3
As known, implementation of an interface Set can not contain the same objects.
In our case, 3 objects will be placed in Set. Objects user1 and user3 are not the same, despite the fact that the equals() method returns true while comparing these objects. It is not enough to override only equals() method.
Equal object must have also the same hash code. In order to do this, you must override the hashCode(). The correct answer - 3 will be printed..

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Sign Up Now
or Subscribe for future quizzes