本文共 1907 字,大约阅读时间需要 6 分钟。
我现在比较喜欢看API相关文档了,总会有些特别的收获的。比如这一次我发现,原来String的某些方法,我一直都理解错了。
toLowerCase & toUpperCase
public String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale. This is equivalent to calling toLowerCase(Locale.getDefault()).
Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "TITLE".toLowerCase() in a Turkish locale returns "t\u0131tle", where '\u0131' is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, use toLowerCase(Locale.ROOT).
Returns:
the String, converted to lowercase.
See Also:
toLowerCase(Locale)
public String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale. This method is equivalent to toUpperCase(Locale.getDefault()).
Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "title".toUpperCase() in a Turkish locale returns "T\u0130TLE", where '\u0130' is the LATIN CAPITAL LETTER I WITH DOT ABOVE character. To obtain correct results for locale insensitive strings, use toUpperCase(Locale.ROOT).
Returns:
the String, converted to uppercase.
See Also:
toUpperCase(Locale)
如上所言,“LITTLE”.toLowerCase()在不同的语言环境下返回的结果是不同的,也就是说,toLowerCase()方法(注意,这里是无参数的方法)是区域敏感的。而如果想得到统一的结果的话,可以调用toLowerCase(Locale.ROOT) (Java 8的建议)或toLowerCase(Locale.ENGLISH) (Java 7以前的建议)。toUpperCase同理。
如果在业务逻辑中大小写敏感的话,极不推荐toLowerCase()方法,因为无法确保软件是否会跨区域使用,万一有跨区域使用情形,将会带来难以排查的bug。
思考:
如果大小写转化只是用于显示的话,建议用默认的无参数方法即可。而如果大小写转化用于业务逻辑的话,强烈建议采用指定Locale.ROOT或Locale.ENGLISH的方法。
转载地址:http://ohqhp.baihongyu.com/