简体   繁体   English

为什么编译器不给出错误或警告列表l = new LinkedList <String> ()

[英]Why compiler not give error or give warning for List l = new LinkedList<String>()

Let me explain the scenario. 让我解释一下情况。

If i am not wrong, Generics in java are only for compile time type safety. 如果我没有错, Genericsjava是仅适用于编译时类型安全。 If i write 如果我写

List<String> list = new LinkedList<String>();  // fine
list.add("test");  // fine

which is fine.But If i write 很好。但是如果我写

List list = new LinkedList<String>();  // fine
list.add(9);  // fine

Here i have created LinkedList of String and List variable is pointing to LinkedList . 在这里,我创建了String的LinkedList ,并且List变量指向LinkedList It is allowing to insert integer into list . 允许将integer插入list

Now, Generics are related to types.Here Type is List and i have not written generics for that ie List<String> list So writing generics at right side while creating object and not writing at left side doesn't make List generic . 现在, GenericsType有关。这里的TypeList ,我还没有为此写generics ,即List<String> list所以在创建object在右侧写generics而不在左侧写generics不会使List generic So why compiler doesn't give warning ar exception at run/compile time for following statement 那么,为什么编译器在运行/编译时不对以下语句发出警告ar异常

List list = new LinkedList<String>();

Is it useless to write such statement while using Generics in java . java使用Generics编写这样的语句是否没有用?

You should not be instantiating the raw type List with the generic type List<T> . 您不应使用通用类型List<T>实例化原始类型List The compiler will give you a warning ; 编译器会警告您; however, this can be done due to Type Erasure . 但是,由于Type Erasure可以完成此操作。

实际上,如果您输入以下内容,则会收到“原始类型”警告:

List list = new LinkedList<String>();

The compiler will display these warnings if you turn compiler warnings on using either 如果您使用以下任一方法打开编译器警告,则编译器将显示这些警告:

-Xlint:rawtypes,unchecked

or 要么

-Xlint:all

See the Non-Standard Options section of the javac docs 请参阅javac文档的“ 非标准选项”部分

From JDK 1.5, Java introduced Generics, which are used to define the type of the contents of a Collection. 从JDK 1.5开始,Java引入了泛型,这些泛型用于定义Collection内容的类型。 If you initialize an ArrayList like this.. 如果您像这样初始化ArrayList。

List list  = new ArrayList();

then the list can contain any type of data, It may be String, Integer or an Object. 那么列表可以包含任何类型的数据,可以是String,Integer或Object。 but if you want to define your List with a particular data type, than you can define it in angular brackets, like this.. 但是如果要使用特定的数据类型定义列表,则可以像这样在尖括号中定义它。

List<String> list  = new ArrayList<String>();

Yes, this will compile with raw type warning and you can insert Object of any type. 是的,这将以原始类型警告进行编译,并且您可以插入任何类型的Object。 It will also work on run time due to Type Erasure. 由于类型清除,它也将在运行时起作用。

But this should be avoided since it doesn't make sense. 但这应该避免,因为这没有意义。

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

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