Java中术语“restricted”的含义是什么?

6
我在关于集合和泛型的章节中的教科书上找到了这个词。 这个句子是:“由于泛型类中的对象类型是受限制的,因此可以在不进行强制转换的情况下访问元素。”简单来说,有人能解释一下这句话的意思吗?

请注意,查看此链接:http://stackoverflow.com/questions/6165822/what-is-this-mean-in-the-arraylist-in-java/6165827#6165827 - Saurabh Gokhale
4个回答

7
当您使用没有泛型的集合时,该集合将接受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

因此,限制是你强制集合只使用一个特定类型,而不是像没有定义泛型签名时那样使用所有内容。


2
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

1
恭喜!这是唯一一个回答问题并且没有多余代码的示例。 - Bohemian
@Bohemian 这是一个要求吗? - Adriaan Koster

1

在这里查看我的答案

由于泛型类中的对象类型受限,因此可以在不进行强制转换的情况下访问元素

使用泛型代码而不是原始类型的优点之一是您无需显式地将结果强制转换回适当的类型。编译器使用一种称为类型擦除的技术隐式完成。

假设,让我们以泛型的例子来说明。

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

这是因为 List 被声明为只存储整数列表。

0
这意味着如果您有一个通用类(例如集合)的类型为 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.

你的整个回答与所问问题无关。请参考@fastcodejava的回答来回答问题。 - Bohemian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接