鍍金池/ 問答/Java/ java泛型為什么不支持原始類型?

java泛型為什么不支持原始類型?

鏈接地址:http://cr.openjdk.java.net/~b...

這里是說由于JVM bytecode對于原始類型和引用類型的字節(jié)碼不相同,為了保持兼容性,故不支持原始類型

At the other end, we have Java's current erased implementation which produces one class for all reference instantiations and no support for primitive instantiations. (This is a homogeneous translation, and the restriction that Java's generics can only range over reference types comes from the limitations of homogeneous translation with respect to the bytecode set of the JVM, which uses different bytecodes for operations on reference types vs primitive types.) However, erased generics in Java provide both behavioral parametricity (generic methods) and data parametricity (raw and wildcard instantiations of generic types.)
To achieve these goals, a homogeneous translation strategy was chosen, where generic type variables are erased to their bounds as they are incorporated into bytecode. This means that whether a class is generic or not, it still compiles to a single class, with the same name, and whose member signatures are the same. Type safety is verified at compile time, and runtime is unfettered by the generic type system. In turn, this imposed the restriction that generics could only work over reference types, since Object is the most general type available, and it does not extend to primitive types.

這里誰能否舉個例子詳細解釋一下,謝謝

回答
編輯回答
純妹

int a = 3的結(jié)果:變量a的值為3。

String s = "hello world"的結(jié)果:s的值為右邊字符串對象在內(nèi)存中的地址。

如果你了解C/C++,那么換句話說,基本類型的變量是一個普通變量,對象類型的變量是一個指針變量。有本質(zhì)不同。

在java中,泛型只是一種表象,或者叫語法糖,它底層是一個Object,而Object是一個指針變量,無法賦值為普通變量。(c/c++支持指針運算,但Java不支持)

2017年4月25日 00:12