开发者

What does the term "restricted" mean in java?

I found the word in my textbook on the chapter about Collections and Generics.

The sentence was

"Since the type of objects in a generic class is restricted, the elements can be accessed without casting."

To put it simply, can someone explain what the sentence m开发者_如何转开发eans?


When you use a collection without generics, the collection is going to accept Object, which means everything in Java (and is also going to give you Object if you try to get something out of it):

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

Once you use generics you restrict the kind of data a collection can hold:

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

So the restriction is that you force the collection to use only one specific type and not everything as it would if you had not defined the generic signature.


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


Check my own answer here.

Since the type of objects in a generic class is restricted, the elements can be accessed without casting

One of the advantage of using Generic code over the raw type is that you need not have to cast the result back into appropriate type explicitly. It is implicitly done by compiler using a technique called Type Erasure.

Suppose, let's take the example of generics.

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

This happens because List was declared to store only list of Integers


It means that if you have a generic class, for example a collection, of type T, you can only put instances of T there.

For example:

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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜