Java 原始类型和泛型交互 [英] Java Raw Type and generics interaction

查看:35
本文介绍了Java 原始类型和泛型交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 Stack 类

If I have a Stack class

class Stack<E> {}

现在如果我这样做:

1) Stacks = new Stack()

2) Stack s = new Stack()

3) Stack s = new Stack()

谁能向我解释这些相互作用(通用<->原始)的原因是什么?

can anyone explain me what these interactions (generic<->raw) causes?

我的疑问主要在于第 1 点.事实上,如果我这样做,则赋值是不安全的,因为该堆栈可以存储除 Integer 以外的类型.是的,但如果我有一个推送方法并尝试存储一个不是整数的值编译器会阻止我......所以当我有那个不安全的操作时?

Mainly my doubt is on point 1. In fact if I do that the assignment it's unsafe because that stack can store types other then Integer. Yes but if I have a push method and try to store a value othern than an Integer the compiler stop me...so when I'd have that unsafe operation?

推荐答案

所有三个都是完全合法的,因为 StackStack,但所有三个都会导致编译器警告.

All three are perfectly legal, since there is no actual runtime difference between a Stack and a Stack<Integer>, but all three will result in compiler warnings.

Stack<Integer> s = new Stack()

这将导致未经检查的转换"警告,因为通常将原始类型转换为参数化类型是不安全的.但是,在这种情况下这样做是完全安全的:推送 Integer 值不会导致任何错误;推送非Integer 值将导致类型错误.

This will result in an "unchecked conversion" warning, because it's not safe in general to convert a raw type to a parameterized type. However, it's perfectly safe to do so in this case: pushing Integer values will not cause any errors; pushing non-Integer values will cause a type error.

Stack s = new Stack<Integer>()

这是从参数化类型到原始类型的合法转换.您将能够推送任何类型的值.但是,任何此类操作都会导致未检查调用"警告.

This is a legal conversion from a parameterized type to a raw type. You will be able to push value of any type. However, any such operation will result in an "unchecked call" warning.

Stack s = new Stack()

同样,这是合法的,没有隐式转换.您将能够推送任何类型的值.但是,任何此类操作都会导致未检查调用"警告.

Again, this is legal, with no implicit conversion. You will be able to push value of any type. However, any such operation will result in an "unchecked call" warning.

您也可能在任何时候引用类型 Stack 时收到原始类型"警告.

You may also get a "raw type" warning any time you refer to the type Stack.

这篇关于Java 原始类型和泛型交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆