简体   繁体   English

Java Generics - 原始类型与非泛型类型有何不同

[英]Java Generics - How is a raw type different from a non generic type

In java generics context, a raw type is a non-parameterized invocation of a generic type. 在java泛型上下文中,原始类型是泛型类型的非参数化调用。 They also say that any non-generic type is not a raw type. 他们还说任何非泛型类型都不是原始类型。

My confusion is, why they say that non-generic type is not a raw type? 我的困惑是,为什么他们说非泛型类型不是原始类型? How is it different from a non-parameterized invocation of a generic type. 它与泛型类型的非参数化调用有何不同? Consider the following 2 cases. 考虑以下2个案例。

Case 1: 情况1:

class A<T>{

}
A a = new A(); //Raw type

Case 2: 案例2:

class A{

}
A a = new A();//Non-generic type

If variable "a" behaves identically in both cases, why do they say case[1] is raw type while case[2] is not? 如果变量“a”在两种情况下表现相同,为什么他们说case [1]是原始类型而case [2]不是?

The concept of raw type is only relevant to generic types due to the issue that the raw type is considered to be assignment-compatible with the generic type, but doing such assignment opens a loophole in type safety otherwise guaranteed for the generic type. 原始类型的概念仅与泛型类型相关,因为原始类型被认为是与泛型类型的赋值兼容的问题,但是这样的赋值打开了类型安全的漏洞,否则保证泛型类型。 For example, consider a method void workWith(A<Integer> a) . 例如,考虑一个方法void workWith(A<Integer> a) You will be allowed to pass in your a variable, resulting in a type safety incident. 您将被允许传入您a变量,从而导致类型安全事件。

As non-generic types cannot suffer from such issues, they are not termed "raw types". 由于非泛型类型不会受到这些问题的影响,因此它们不被称为“原始类型”。

As said in JLS : JLS所述:

A non-generic class or interface type is not a raw type. 非泛型类或接口类型不是原始类型。

You can feel the difference in the syntactic level : 你可以感受到句法 层面的差异:

if we have parameterized class: 如果我们有参数化类:

class A<X> {
   class B<Y> {
      Y y;
   }
}

then just A name type or B name type aren't non-generic types, they are raw types, and this influences on how you can access to them: 然后只是A名称类型或B名称类型不是non-generic类型,它们是raw的类型,以及如何访问它们此影响:

all this constructions will cause compile time error: 所有这些结构都会导致编译时错误:

A<Integer>.B ab = null;
A.B<Integer> ab = null;

Raw type has to do with the bounding of generic types and type erasure. 原始类型与泛型类型和类型擦除的边界有关。 If you have ArrayList<? extends Shape> 如果你有ArrayList<? extends Shape> ArrayList<? extends Shape> then the bound type is Shape and will be the raw type at compile time. ArrayList<? extends Shape>然后绑定类型是Shape,并且在编译时将是原始类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM