Common Gotchas
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:
Comparing equality of objects using ==
instead of .equals()
-- which behaves completely differently for primitives.
This gotcha ensures newcomers are befuddled when "foo" == "foo"
but new String("foo") != new String("foo")
.
"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.
Overriding equals() but not hashCode()
It can have really unexpected results when using maps, sets or lists.
链接地址: http://www.djcxy.com/p/17898.html上一篇: 用PHP替换JAVA以实现PKCS5加密
下一篇: 共同的问题