Your question is "How can I be sure that my class is immutable?" I'm not sure that's what you mean to ask, but the way to make your class immutable is listed by Josh Bloch in Effective Java, 2nd Ed. in item 15 here, and which I'll summarize in this answer:
- Don't provide any mutator methods (methods that change the object's state, usually called "setters").
- Ensure the class can't be extended. Generally, make the class final. This keeps others from subclassing it and modifying protected fields.
- Make all fields final, so you can't change them.
- Make all fields private, so others can't change them.
- "Ensure exclusive access to mutable components." That is, if something else points to the data and therefore can alter it, make a defensive copy (as @user949300 pointed out).
Note that immutable objects don't automatically yield a the big performance boost. The boost from immutable objects would be from not having to lock or copy the object, and from reusing it instead of creating a new one. I believe the searches in HashMap use the class' hashCode()
method, and the lookup should be O(c)
, or constant-time and fast. If you are having performance issues, you may need to look at if there's slowness in your hashCode()
method (unlikely), or issues elsewhere.
One possibility is if you have implemented hashCode()
poorly (or not at all) and this is causing a large number of collisions in your HashMap
-- that is, calling that method with different instances of your class returns mostly similar or same values -- then the instances will be stored in a linked list at the location specified by hashCode()
. Traversing this list will convert your efficiency from constant-time to linear-time, making performance much worse.