D’oh…..

Over on his blog, Peter sometimes like to tease people with the odd puzzle or so. Over the Easter holidays, I have been playing with Java Sets a bit and promptly fell into a trap. Now as is usual with these things, particularly if you are somewhat of a Java “noob” like me, it took me a while to figure out what went wrong. And in the spirit of sharing and joint pain, I thought I should do a puzzle too and blog this one……it might keep some of you amused. Here is the little toy programme I was playing with at the time:

code.jpg

(Apologies for the code being in a pic – WordPress messes with the angle brackets) Looks easy enough, right? And I promise you it compiles and runs. Now, without running it, what do you think it prints? Now run it. What does it print? Did you expect what it printed (if so, congratulations…..:-)). If not, what could be the reason?

3 Responses to D’oh…..

  1. petermr says:

    I am writing before running it… I would never use these constructs myself… I suspect the answer will depend on the version of Java that is being used. The fact that it compiles suggests that the short (sic) is being autoboxed into a Short (sic). Collection classes use first-class objects (Short) so that presumably add(i) is compiled as add (new Short(i)). The identity of objects in a Set depend on how the equals() and hashCode() methods are implemented. I don’t know from memory whether
    new Short(1) .equals(new Short(2-1));

    My guess is that the set will contain 10 objects… now I shall test it.

  2. petermr says:

    Yes. However if you write:
    Set testSet = new HashSet();
    for (short i = 0; i < 10; i++) {
    testSet.add(new Short(i));
    testSet.remove(new Short((short)(i-1)));
    }
    System.out.println(testSet.size());
    The answer is 1

    However if I change Short to Integer and write:
    Set testSet = new HashSet();
    for (int i = 0; i < 10; i++) {
    testSet.add(i);
    testSet.remove(i-1);
    }
    System.out.println(testSet.size());
    then I get 1. The reason is that two Integers are regarded as equals() if the have the same value.

    I never use short – I don’t trust it. And I would always convert primitives to first-class objects.

    This is not a trivial area. Many people have run foul of it.

  3. Pingback: Unilever Centre for Molecular Informatics, Cambridge - Staudinger’s Semantic Molecules » Blog Archive » D’oh solved…..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: