Wednesday, October 8, 2008

Obscure Things Every Java Developer Should Know Depending On Who You Talk To

In my career, I have found that the best way to learn something is to give a presentation on it. In lieu of that, perhaps writing about it would be a good way to make it sink in, and hopefully someone else can stumble across it and benefit from it as well. Here are some of those things:

hashCode() v. equals()

The following comes from this awesome site

All objects have both identity (the object's location in memory) and state (the object's data). The == operator always compares identity. The default implementation of equals compares identity as well. Fun facts:
  • if a class overrides equals, it must override hashCode
  • when they are both overridden, equals and hashCode must use the same set of fields
  • if two objects are equal, then their hashCode values must be equal as well
From an interesting blog post on hashmaps and hashcode():
When an object is inserted into a HashMap, the position at which the Value object is inserted in its internal Entry-array depends on the hashCode of the Key object passed in. The hashCode generated by the Key object is not used directly, but is processed by the hash(k) method.
Immutable Objects

What is an immutable object?

Immutable objects are simply objects whose state (the object's data) cannot change after construction.

Why are they so good? They:
  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • do not need a copy constructor
  • do not need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • do not need to be copied defensively when used as a field
  • make good Map keys and Set elements (these objects must not change state while in the collection)
Wanna learn this stuff visually, without paying tuition??

CHECK THIS OUT - Cal Berkely Data Structures Lectures (kinda awesome)

This is one of those "man the internets are sweet" type things. I will use this to learn all the nasty bits that I don't really want to but might have to.