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

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

问题描述

如果我有一个Stack类

  class Stack< E> {} 

现在如果我这样做:

1)堆栈<整数> s = new Stack()



2) Stack s = new Stack< Integer>() $ b <3> Stack s = new Stack()



任何人都可以向我解释这些交互(通用 - >原始)是什么原因造成的?



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

Stack 和a 之间没有实际的运行时间差异,所以三者完全合法。>解决方案 Stack< Integer> ,但所有这三个都会导致编译器警告。

s = new Stack()

这会导致未检查转换警告,因为它不安全通常将原始类型转换为参数化类型。但是,在这种情况下完全可以这么做:推送整数值不会导致任何错误;推送非 - 整型值将导致类型错误。

  Stack s = new Stack< Integer>()

这是从参数化类型到原始类型的合法转换。你将能够推动任何类型的价值。然而,任何这样的操作都会导致unchecked call警告。

  Stack s = new Stack()

同样,这是合法的,没有隐式转换。你将能够推动任何类型的价值。然而,任何这样的操作都会导致unchecked call警告。



每当您引用类型<$ c时,您也可能会收到原始类型警告$ c> Stack 。


If I have a Stack class

class Stack<E> {}

now if I do:

1) Stack<Integer> s = new Stack()

2) Stack s = new Stack<Integer>()

3) Stack s = new Stack()

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

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?

解决方案

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()

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.

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

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

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