我试图将 Unicode 字符 0x10FFFF
分配给 char
,但失败并出现错误:
public static void main(String []args){
char a = 0x10FFFF;
int b=a;
System.out.println("b="+b+", but a="+a);
}
错误:
HelloWorld.java:4: error: possible loss of precision
char a= 0x10FFFF;
^
required: char
found: int
1 error
现在我知道 char
的上限是 65,535,因为它使用 16 位进行存储。
这是否意味着 char
不应该用来表示 Unicode 字符?在处理 Unicode 字符时,我们应该始终使用 int
吗?
那么 char
类型有什么用呢?
最佳答案
Does that mean that a char should never be used to represent Unicode characters?
不,Basic Multilingual Plane 中的 Unicode 字符仍然可以用 char
表示。
Should we always use an int when dealing with Unicode characters?
不,使用 String
和 Surrogate Pairs .例如。使用 "\uD83C\uDF84"
来表示 Unicode 字符 'CHRISTMAS TREE' (U+1F384)。这里有一个很好的代理对计算器:http://www.russellcottrell.com/greek/utilities/SurrogatePairCalculator.htm
What good is the char type then?
它仍然可以表示 在基本多语言平面中的任何字符。
关于java - 将大小为 4 字节的 Unicode 字符分配给 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23204777/