Java Programming - Objects and Collections - Discussion

Discussion Forum : Objects and Collections - Pointing out the correct statements (Q.No. 1)
1.
class Test1 
{
    public int value;
    public int hashCode() { return 42; }
}
class Test2 
{
    public int value;
    public int hashcode() { return (int)(value^5); }
}
which statement is true?
class Test1 will not compile.
The Test1 hashCode() method is more efficient than the Test2 hashCode() method.
The Test1 hashCode() method is less efficient than the Test2 hashCode() method.
class Test2 will not compile.
Answer: Option
Explanation:

The so-called "hashing algorithm" implemented by class Test1 will always return the same value, 42, which is legal but which will place all of the hash table entries into a single bucket, the most inefficient setup possible.

Option A and D are incorrect because these classes are legal.

Option B is incorrect based on the logic described above.

Discussion:
14 comments Page 2 of 2.

Nickc-88 said:   1 decade ago
Since variable value initialised with default value=0 class Test1 hashCode will be more efficient, because it only returns 42, but in Test2 it always performs arithmetic operation (0^5) and then returns value.

Jimbo said:   1 decade ago
This question is not ideal.

In terms of efficiency, Test1's hashCode () method is marginally more efficient since no arithmetic is performed.

For the purpose of a hash table, they are both useless methods since each always returns the same value - 42 and 0 respectively (we never know if Test2's "value" member will ever be changed, thus we can only assume it always has the default value of 0).

Nafeez Abrar said:   1 decade ago
It is not mentioned here that, the function hashcode() is return actually a hash value for a hash table or other purpose.

Kalai said:   1 decade ago
In this class "value" is not initialized then how the operation (value^5) can be performed.

class Test2
{
public int value;
public int hashcode() { return (int)(value^5); }
}


Post your comments here:

Your comments will be displayed after verification.