我在教科书中找到了关于集合和泛型的章节.
这句话是
"由于泛型类中的对象类型受到限制,因此可以在不进行转换的情况下访问元素."
简单来说,有人可以解释这句话的含义吗?
当您使用没有泛型的集合时,该集合将接受Object,这意味着Java中的所有内容(如果您尝试从中获取某些内容,它也将为您提供Object):
List objects = new ArrayList();
objects.add( "Some Text" );
objects.add( 1 );
objects.add( new Date() );
Object object = objects.get( 0 ); // it's a String, but the collection does not know
Run Code Online (Sandbox Code Playgroud)
使用泛型后,您可以限制集合可以容纳的数据类型:
List<String> objects = new ArrayList<String>();
objects.add( "Some text" );
objects.add( "Another text" );
String text = objects.get( 0 ); // the collection knows it holds only String objects to the return when trying to get something is always a String
objects.add( 1 ); //this one is going to cause a compilation error, as this collection accepts only String and not Integer objects
Run Code Online (Sandbox Code Playgroud)
因此,限制是强制集合仅使用一种特定类型,而不是像未定义通用签名那样使用所有内容.
这意味着如果您有一个类型为 的泛型类(例如集合)T,则只能将其实例放在T那里。
例如:
List<String> onlyStrings = new ArrayList<String>();
onlyStrings.add("cool"); // we're fine.
onlyStrings.add("foo"); // still fine.
onlyStrings.add(1); // this will cause a compile-time error.
Run Code Online (Sandbox Code Playgroud)