我在教科书中关于集合和泛型的章节中找到了这个词。
这句话是
"Since the type of objects in a generic class is restricted, the elements can be accessed without casting."
简单来说,谁能解释一下这句话的意思?
最佳答案
当你使用一个没有泛型的集合时,集合将接受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
一旦你使用了泛型,你就限制了一个集合可以保存的数据类型:
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
因此限制是您强制集合仅使用一种特定类型,而不是像您没有定义通用签名时那样使用所有类型。
关于java - 术语 "restricted"在 Java 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6811147/