Choosing between CharSequence and String for an API [duplicate]

别来无恙 提交于 2019-11-27 02:36:04

问题


This question already has an answer here:

  • When to use CharSequence in an API 5 answers

A String is-a CharSequence. Many methods in the Java library accept CharSequence so they operate more generally. Some classe have a String method (for example, Writer.write(String)) and also implement Appendable with an equivalent CharSequence method (for example, Writer.append(CharSequence)).

If I am writing a class that delegates to such a class, ands needs some text input, I can choose for that input to be a String or a CharSequence. Choosing the later makes the class more flexible, by giving the client more options. But I don't see much code that does so: text arguments are almost invariably a String rather than a CharSequence. Is there a down-side to using CharSequence? Is there a performance hit? Or is it just programmer intertia or ignorance that causes use of String rather than CharSequence?

Compare

class XMLWriter {
   private final Writer writer;

   // more stuff here

   public void writeComment(String text) {
      writer.write("<!-- ");
      writer.write(text);
      writer.write(" -->");
   }
}

with

class XMLWriter {
   private final Writer writer;

   // more stuff here

   public void writeComment(CharSequence text) {
      writer.write("<!-- ");
      writer.append(text);
      writer.write(" -->");
   }
}

回答1:


Quoting CharSequence Javadoc:

This interface does not refine the general contracts of the equals and hashCode methods. The result of testing two objects that implement CharSequence for equality is therefore, in general, undefined. 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.

Hence IMO We must think twice before using CharSequnce as a replacement for String.



来源:https://stackoverflow.com/questions/8445311/choosing-between-charsequence-and-string-for-an-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!