我在关于集合和泛型的章节中的教科书上找到了这个词。 这个句子是:“由于泛型类中的对象类型是受限制的,因此可以在不进行强制转换的情况下访问元素。”简单来说,有人能解释一下这句话的意思吗?
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
一旦使用泛型,您将限制集合可以保存的数据类型:
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
因此,限制是你强制集合只使用一个特定类型,而不是像没有定义泛型签名时那样使用所有内容。
List<Animal> animals = new ArrayList<Animal>();
// add some animals to the list.
// now it only had animals not fruits, so you can
Animal animal = animals.get(0); // no casting necessary
在这里查看我的答案
。
由于泛型类中的对象类型受限,因此可以在不进行强制转换的情况下访问元素
使用泛型代码而不是原始类型的优点之一是您无需显式地将结果强制转换回适当的类型。编译器使用一种称为类型擦除
的技术隐式完成。
假设,让我们以泛型的例子来说明。
List<Integer> ls= new ArrayList<Integer>();
ls.add(1); // we're fine.
ls.add(2); // still fine.
ls.add("hello"); // this will cause a compile-time error.
Integer i = ls.get(2); // no explicit type casting required
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.