Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Common Gotchas [closed]

Tags:

java

In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't.

I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for.

See also:

  • Perl - Common gotchas
  • .NET - Common gotchas
like image 771
Alan Avatar asked Oct 04 '08 05:10

Alan


1 Answers

"a,b,c,d,,,".split(",").length 

returns 4, not 7 as you might (and I certainly did) expect. split ignores all trailing empty Strings returned. That means:

",,,a,b,c,d".split(",").length 

returns 7! To get what I would think of as the "least astonishing" behaviour, you need to do something quite astonishing:

"a,b,c,d,,,".split(",",-1).length 

to get 7.

like image 97
butterchicken Avatar answered Sep 19 '22 17:09

butterchicken