Re: question about Collections/Maps
laredotornado@zipmail.com wrote:
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;
Aside: I'd have liked a `final' here.
/** 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;
}
}
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.
--
Eric Sosman
esosman@acm-dot-org.invalid