Skip to content

Java interview prep

April 18, 2008

what is the difference between aggregation and composition
Should we use assertions or exception handling –
Should we catch unchecked exceptions – what is the difference between checked and unchecked exceptions?

equals and hashCode contract = why override hasCode when override equals??
hashCode used when implementing hash based collections like HashMap,HashSet, Hashtable.
it is inherently for better performance. —>hashCode() method exists purely for efficiency

equals=> implies that hashCode must be equal, but if not equal then hashCode may or may not be equal.
. Two different objects may happen to have the same hash code. This is called a “hash collision” and is inevitable if the hashcodes are not the same, then the two objects are not ‘equal’

There are two approaches to defining equality and hash value:
1. identity-based, which is the default provided by Object,
2. state-based, which requires overriding both equals() and hashCode().

If an object’s hash value can change when its state changes, be sure you don’t allow its state to change,
while it is being used as a hash key.
Talks about issues of using equals() in heirarchy and the transitivity that fails.
There are two techniques: using the instanceof operator, which allows mixed-type comparison of subclass and superclass objects. The other choice is using getClass() to make sure that mixed-type comparisons always fail. Another is to use instanceof with state of the specific class while implementing equals.

Need for overriding equals – Two types of classes –
~~ Value types = their state is everything
~~ Entity types = their behaviour is more important – eg: FileOutputStream

1. symmetry [ˈsimitri] noun
the state in which two parts, on either side of a dividing line, are equal in size, shape and position
== a.eq(b) same as b.eq(a)

2. reflexive
reflexive Audio Help (rĭ-flěk’sĭv) Pronunciation Key
Of or relating to a mathematical or logical relation such that, for any given element, that element has the given relation to itself. Equality in mathematics is a reflexive relation, since a = a for all a, whereas the relation of being ‘less than’ is not, since it is not true that a < a for any a.

3. transitive
4. consistent
5. comparision with null.

Great set of articles:


java practices

For me – HashMap = initialCapacity and loadFactor.


Comments are closed.

%d bloggers like this: