Java 当你在没有指定对象类型的情况下创建一个 ArrayList 时,它会在你添加第一个对象时自动创建它吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3936556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:12:12  来源:igfitidea点击:

When you make an ArrayList without specifying the object type, does it create it automatically when you add the first object?

javaarraysobjecttypesarraylist

提问by trusktr

For example, instead of doing

例如,而不是做

ArrayList<ClassName> variableName;

you do

你做

ArrayList variableName;

then later you add an object of type "ClassName"

然后稍后添加一个“ClassName”类型的对象

variableName.add(objectName);

will that automatically set the type of your array as

会自动将数组的类型设置为

ArrayList<ClassName>

?

?

采纳答案by hvgotcodes

No. Generics are for compile time only. You are just losing the benefit of that check. At runtime all generic information is erased

不。泛型仅用于编译时。你只是失去了那张支票的好处。在运行时删除所有通用信息

In other words,

换句话说,

ArrayList<Type> 

at runtime is just an ArrayList. The benefit of doing that over just a List is that when you are writing your code, the compiler will check that you dont put anything inappropriate in your list.

在运行时只是一个 ArrayList。仅使用 List 这样做的好处是,当您编写代码时,编译器会检查您是否没有在列表中放入任何不合适的内容。

回答by stew

when you don't specify, it would be the same as if you specified ArrayList<Object>, meaning that any type of object could be added to the ArrayList. The type checks which are performed when specifying a class happen at compile time, not at runtime, so its not possible for things to work the way you propose (having them more specific class determined at runtime).

如果不指定,则与指定 ArrayList<Object> 相同,这意味着可以将任何类型的对象添加到 ArrayList。指定类时执行的类型检查发生在编译时,而不是运行时,因此不可能按照您建议的方式工作(在运行时确定更具体的类)。

回答by ninjalj

The real type is really ArrayList. The ArrayList<ClassName>type only exists for the compiler (this is called erasure), and its purpose is to give type safety at the compiler level. But at the bytecode level you don't have that knowledge of generic types.

真正的类型是真的ArrayList。该ArrayList<ClassName>类型仅存在于编译器中(这称为擦除),其目的是在编译器级别提供类型安全性。但是在字节码级别,您没有泛型类型的知识。