When to use CharSequence in an API

前端 未结 5 1316
囚心锁ツ
囚心锁ツ 2020-12-14 08:14

I\'m designing a public interface (API) for a package. I wonder, should I use CharSequence generally instead of String. (I\'m mainly talking about

5条回答
  •  甜味超标
    2020-12-14 08:45

    This does depend on what you need, I'd like to state two advantages of String, however.

    From CharSequence's documentation:

    Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map.

    Thus, whenever you need a Map or reliable equals/hashCode, you need to copy instances into a String (or whatever).

    Moreover, I think CharSequence does not explicitly mention that implementations must be immutable. You may need to do defensive copying which may slow down your implementations.

提交回复
热议问题