More Organs → More Human

Stupid things I've figured out so that you don't have to.


Site Feed

Sunday, November 27, 2005

LinkedHashSet

Did you know that you can add null to a LinkedHashSet, and have it take up space and appear in an Iterator? Neither did I, until just now.



00001: LinkedHashSet lhs = new LinkedHashSet();
00002:
00003: lhs.add(null);
00004:
00005: System.out.println(lhs.size()); // outputs 1



Something about this doesn't seem quite right to me, but I'm not sure what. I guess I'm used to null sort of being, well, null.

Also, Ruby's officially spoiled me. I've grown horribly used to its excellent "unless" syntax. For instance, to only add something to a collection if it's not null is one line in Ruby:



00001: someCollection.add(foo) unless foo.nil?



In Java, however, it's quite a process:



00001: if (foo != null) {
00002: someCollection.add(foo);
00003: }



It's only a few more lines, but it really messes with the flow of typing somehow. Maybe I'll hack together a quick IntelliJ macro or something...

1 Comments:

Blogger Jeff said...

I don't know... isn't having a null item in a linked list something like saying: "here's a box that contains nothing?" So when you get the size of that list, it's saying "there's one box" regardless of what's in it. But yes. It's a little strange that a list of one null element has a size of 1.

Nice blog, by the way. =)

6:10 PM  

Post a Comment

<< Home