Hi, I got this question on an interview. My gut instinct is no, but I
can't justify the reasons. Any insight is greatly appreciated.
Assume you are writing an application working with ID objects. The
application uses these ID objects in Collections, placing them into
Collection implementations and querying if IDs are in a Collection
using the method Collection.contains(). The application also uses ID
objects as keys in Maps, to associate an ID with another Object and to
efficiently lookup those Objects based on ID. Will the following
implementation of ID work in our application, given the usages listed
above? If not, please fix it so that it will. (Note: the following code
compiles fine.)
/** An ID is just a String */
public class ID {
/** The ID value */
private String _id;
/** Construct an ID given its String value */
public ID(String id) {
if (id == null)
throw new NullPointerException();
_id = id;
}
/** Get the ID value */
public String getID() {
return _id;
}
}
Thanks, -
Matt Humphrey - 27 Jul 2006 03:55 GMT
> Hi, I got this question on an interview. My gut instinct is no, but I
> can't justify the reasons. Any insight is greatly appreciated.
[quoted text clipped - 27 lines]
> }
> }
The answer is no because two distinct IDs with the same _id contents will
test false for equals. You must override equals and hashcode.
Cheers,
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/
Eric Sosman - 27 Jul 2006 04:05 GMT
> Hi, I got this question on an interview. My gut instinct is no, but I
> can't justify the reasons. Any insight is greatly appreciated.
[quoted text clipped - 13 lines]
> /** The ID value */
> private String _id;
Aside: I'd have liked a `final' here.
> /** Construct an ID given its String value */
> public ID(String id) {
[quoted text clipped - 9 lines]
> }
> }
I think the answer they're fishing for is "No," with the
explication being "because you really ought to do something
about the equals() and hashCode() methods."
Don't you just hate these "cooked" questions? Somebody
pops one at you and sits there smirking; you can almost hear
him singing "I know the an-swer, nya nya nya nyahhh-nya!" If
you give him his bloody useless answer, what has he learned
about your abilities? That you're a perspicacious and thoughtful
practitioner, or that you've read a load of puzzle books?
Mime interviews Wotan and asks a bunch of tricksy questions
to trip him up. Wotan has the answers (he's a god, after all),
and when it comes his turn to ask questions of Mime he observes
that Mime has made a fundamental error: Granted an opportunity
to partake of a god's knowledge, he has wasted his time asking
questions whose answers he already knows. The answers thus
benefited him not at all; he should instead have asked about
what he *didn't* know, and thereby learned something.
Ponder that, next time you're interviewing someone -- from
either side of the desk.

Signature
Eric Sosman
esosman@acm-dot-org.invalid