在API的CharSequence和String之间进行选择 [英] Choosing between CharSequence and String for an API

查看:151
本文介绍了在API的CharSequence和String之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A String 是-a CharSequence 。 Java库中的许多方法接受 CharSequence ,因此他们的运作更为普遍。有些classe有一个 String 方法(例如, Writer.write(String))并且还实现 Appendable ,带有等效的 CharSequence 方法(例如, Writer.append(CharSequence))。

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)).

如果我正在编写一个委托给这样一个类的类,并且需要一些文本输入,我可以选择输入为 String CharSequence 。通过为客户提供更多选项,选择后者可以使课程更加灵活。但是我没有看到太多代码这样做:文本参数几乎总是 String 而不是 CharSequence 。是否有使用 CharSequence 的缺点?是否有性能受损?或者只是程序员的intertia或无知导致使用 String 而不是 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?

比较

class XMLWriter {
   private final Writer writer;

   // more stuff here

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

class XMLWriter {
   private final Writer writer;

   // more stuff here

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


推荐答案

As每个javadoc的 CharSequence

As per javadoc of CharSequence


此接口不会细化equals和
hashCode方法的常规协定。因此,比较实现
CharSequence的两个对象的结果通常是未定义的。每个对象可能是由另一个类实现的
,并且不能保证每个$​​ b $ b类能够测试其实例是否与另一个的
相等。因此,不宜将任意
CharSequence实例用作集合中的元素或映射中的键。

This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence 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.

因此IMO在使用CharSequnce作为String的替代品之前,我们必须三思而行。

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

这篇关于在API的CharSequence和String之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆