gpt4 book ai didi

java - 为 API 在 CharSequence 和 String 之间进行选择

转载 作者:IT老高 更新时间:2023-10-28 20:54:20 26 4
gpt4 key购买 nike

A String is-a CharSequence . Java 库中的许多方法都接受 CharSequence所以they operate more generally .有些类(class)有 String方法(例如 Writer.write(String) )并实现 Appendable具有等价的 CharSequence方法(例如,Writer.append(CharSequence))。

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

最佳答案

引用 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.

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

关于java - 为 API 在 CharSequence 和 String 之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com