在ArrayList上指定类型参数的位置 [英] Where to specify type parameter on ArrayList
问题描述
List< String> myNumbers = new ArrayList< String>( );
与:
List< String> myNumbers = new ArrayList();
和:
List myNumbers = new ArrayList< String>();
第一个例子是类型安全含义,将 String
对象添加到 myNumbers
列表中,然后您将收到编译器错误。
列表< String> myNumbers = new ArrayList< String>();
第二个例子也是类型安全的,编译器将确保只有<$ c $类型的对象c>字符串存储在 myNumbers
列表中。
List< String> myNumbers = new ArrayList();
原始类型
当泛型是在JDK 1.5中引入的原始类型只保留用于向后兼容老版本的Java。虽然使用原始类型仍然是允许的,但您应该避免出于以下原因:
最后一个例子是一个原始类型,意思是我们可以添加所有类型的对象转换为 myNumbers
列表,但是,您应该尽可能避免它们。
List myNumbers = new ArrayList< String>();
注意 - 如果您没有指定类型, myNumbers
列表中的每个项目都被视为类型 Object
。
在ArrayList中指定类型参数的位置?
从您展示的示例中,您首选的方式是:
列表< String> myNumbers = new ArrayList< String>();
但是,您可以用一个空集替换调用泛型类的构造函数所需的类型参数( 不是这个意思: 我们可以这样做: What is the difference between casting on both sides: versus: and:
The first example is type safe meaning if you attempt to add anything other than a The second example is also type-safe, the compiler will ensure only objects of type
< / code>
>
),只要编译器可以从上下文中推断出类型参数。 / b>
List< String> myNumbers = new ArrayList< String>();
列表< String> myNumbers = new ArrayList<>();
List <String>myNumbers = new ArrayList<String>();
List <String>myNumbers = new ArrayList();
List myNumbers = new ArrayList<String>();
String
object into myNumbers
list then you'll get a compiler error.List <String> myNumbers = new ArrayList<String>();
String
are stored in myNumbers
list.List <String> myNumbers = new ArrayList();
Raw Types
A raw type is the name of a generic class or interface without any type arguments.
When generics were introduced in JDK 1.5, the raw types were retained only for backwards compatibility with older versions of java. Though using raw types is still permissible, you should avoid them for the reasons below:
- typically raw types require casts
- raw types are NOT type safe and some important kinds of errors will only appear at runtime.
- raw types are less expressive & don't self-document in the same way as parameterized types.
The last example is a raw type meaning we can add all type of objects into myNumbers
list, However, you should avoid them when you can.
List myNumbers = new ArrayList<String>();
note - if you do not specify the type, as shown above, every item within myNumbers
list is treated as a type Object
.
Where to specify type parameter on ArrayList?
From the examples you've shown this is the preferred way:
List <String> myNumbers = new ArrayList<String>();
However, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<
>
) as long as the compiler can infer the type arguments from the context.
meaning instead of this:
List <String> myNumbers = new ArrayList<String>();
we can do this:
List <String> myNumbers = new ArrayList<>();
这篇关于在ArrayList上指定类型参数的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!