java创建集合有的不用泛型_为什么在Java泛型右手边的集合类型没有任何影响?...
使用Java的Generics功能我創建了一個List對象,在左側我使用的是原始類型List,在右側我使用的是泛型類型ArrayList.
List myList=new ArrayList();
我在list對象中添加了一個int值.
myList.add(101);
我希望我會得到一些編譯錯誤但是這個程序運行正常.但是如果我使用泛型類型List在左側和右側的原始類型ArrayList并嘗試將int值添加到列表中,我按預期收到編譯錯誤.
List myList=new ArrayList();
myList.add(101);//The method add(int, String) in the type List is not applicable for the arguments (int)
為什么在Java泛型右手邊的集合類型沒有任何影響?為什么Java允許我們在沒有任何影響時這樣做.我正在使用Java 1.6.請解釋.
解決方法:
如果您未在左側提供泛型類型參數,則將List聲明為原始類型.這意味著編譯器不知道在該列表中存儲什么是合法的,并且依賴于程序員來執行適當的檢查和轉換實例.
原始類型還具有在它們出現的類中刪除所有泛型類型信息的效果.
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.
標簽:java,collections,generics,java-6
來源: https://codeday.me/bug/20190829/1764170.html
總結
以上是生活随笔為你收集整理的java创建集合有的不用泛型_为什么在Java泛型右手边的集合类型没有任何影响?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java创建一个文件变量_java如何定
- 下一篇: 我的世界一进去就java_我的世界国际j