java创建集合有的不用泛型_为什么在Java泛型右手边的集合类型没有任何影响?...
使用Java的Generics功能我創(chuàng)建了一個(gè)List對(duì)象,在左側(cè)我使用的是原始類(lèi)型List,在右側(cè)我使用的是泛型類(lèi)型ArrayList.
List myList=new ArrayList();
我在list對(duì)象中添加了一個(gè)int值.
myList.add(101);
我希望我會(huì)得到一些編譯錯(cuò)誤但是這個(gè)程序運(yùn)行正常.但是如果我使用泛型類(lèi)型List在左側(cè)和右側(cè)的原始類(lèi)型ArrayList并嘗試將int值添加到列表中,我按預(yù)期收到編譯錯(cuò)誤.
List myList=new ArrayList();
myList.add(101);//The method add(int, String) in the type List is not applicable for the arguments (int)
為什么在Java泛型右手邊的集合類(lèi)型沒(méi)有任何影響?為什么Java允許我們?cè)跊](méi)有任何影響時(shí)這樣做.我正在使用Java 1.6.請(qǐng)解釋.
解決方法:
如果您未在左側(cè)提供泛型類(lèi)型參數(shù),則將List聲明為原始類(lèi)型.這意味著編譯器不知道在該列表中存儲(chǔ)什么是合法的,并且依賴(lài)于程序員來(lái)執(zhí)行適當(dāng)?shù)臋z查和轉(zhuǎn)換實(shí)例.
原始類(lèi)型還具有在它們出現(xiàn)的類(lèi)中刪除所有泛型類(lèi)型信息的效果.
To make sure that potential violations of the typing rules are always
flagged, some accesses to members of a raw type will result in
compile-time unchecked warnings. The rules for compile-time unchecked
warnings when accessing members or constructors of raw types are as
follows:
At an assignment to a field: if the type of the left-hand operand is a
raw type, then a compile-time unchecked warning occurs if erasure
changes the field’s type.
At an invocation of a method or constructor: if the type of the class
or interface to search (§15.12.1) is a raw type, then a compile-time
unchecked warning occurs if erasure changes any of the formal
parameter types of the method or constructor.
No compile-time unchecked warning occurs for a method call when the
formal parameter types do not change under erasure (even if the result
type and/or throws clause changes), for reading from a field, or for a
class instance creation of a raw type.
標(biāo)簽:java,collections,generics,java-6
來(lái)源: https://codeday.me/bug/20190829/1764170.html
總結(jié)
以上是生活随笔為你收集整理的java创建集合有的不用泛型_为什么在Java泛型右手边的集合类型没有任何影响?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java创建一个文件变量_java如何定
- 下一篇: JAVA项目实训struts2_Java