問(wèn)題描述
關(guān)于原語(yǔ):當(dāng)我從較小的類(lèi)型轉(zhuǎn)換為較大的類(lèi)型時(shí),轉(zhuǎn)換是隱式的,當(dāng)我從較大的類(lèi)型轉(zhuǎn)換為較小的類(lèi)型時(shí),我需要顯式地轉(zhuǎn)換原語(yǔ),由于數(shù)據(jù)丟失,這很明顯.但有些東西我不明白.當(dāng)我在某些情況下(字節(jié)和短)向上或向下轉(zhuǎn)換為 char 時(shí),我總是需要在兩個(gè)方向上顯式轉(zhuǎn)換,盡管 byte(8 位)適合 char(16 位)?
Concerning primitives: When I cast from smaller to bigger types, the casts are implicit, when I cast from bigger to smaller types, I need to explicitly cast the primitives, that's clear due to loss of data. But there is something I don't get. When I up- or downcast to char in some cases (byte and short), I always need to explicitly cast in both directions although byte (8bit) fits into char (16bit)?
(另請(qǐng)參見(jiàn) http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)
看我的例子...
public class CastingTest
{
public static void main(String[] args)
{
//casting from smaller to bigger types
short c = 13;
int d = c;
byte f = 34;
short g = f;
byte h = 20;
long i = h;
byte var03 = 6;
double var04 = var03;
//casting from bigger to smaller types
int j = 12;
short k = (short)j;
long m = 56;
int n = (int)m;
double o = 19;
short p = (short)o;
//not possible without explicit cast, but why?
byte var01 = 3;
char var02 = (char)var01;
short var05 = 5;
char var06 = (char)var05;
char var07 = 'k';
short var08 = (short)var07;
}
}
推薦答案
char
是 Java 唯一的 unsigned 類(lèi)型,因此它的取值范圍不完全包含任何其他 Java 類(lèi)型的值范圍.
char
is Java's only unsigned type, therefore its value range does not fully contain any other Java type's value range.
對(duì)于目標(biāo)類(lèi)型范圍未完全覆蓋源類(lèi)型范圍的任何轉(zhuǎn)換,您必須使用顯式轉(zhuǎn)換運(yùn)算符.
You must use an explicit cast operator for any conversion where the target type's range doesn't fully cover the source type's range.
這篇關(guān)于為什么我需要在 byte 和 short 上顯式轉(zhuǎn)換 char 原語(yǔ)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!