Why is there no String.Empty in Java?

前端 未结 12 1446
悲哀的现实
悲哀的现实 2020-12-07 15:11

I understand that every time I type the string literal \"\", the same String object is referenced in the string pool.

But why doesn\'t the String API in

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 15:59

    Don't just say "memory pool of strings is reused in the literal form, case closed". What compilers do under the hood is not the point here. The question is reasonable, specially given the number of up-votes it received.

    It's about the symmetry, without it APIs are harder to use for humans. Early Java SDKs notoriously ignored the rule and now it's kind of too late. Here are a few examples on top of my head, feel free to chip in your "favorite" example:

    • BigDecimal.ZERO, but no AbstractCollection.EMPTY, String.EMPTY
    • Array.length but List.size()
    • List.add(), Set.add() but Map.put(), ByteBuffer.put() and let's not forget StringBuilder.append(), Stack.push()

提交回复
热议问题