Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the term "restricted" mean in java?

Tags:

java

generics

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 means?

like image 936
WhiskeyTangoFoxtrot Avatar asked Jul 25 '11 01:07

WhiskeyTangoFoxtrot


1 Answers

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.

like image 65
Maurício Linhares Avatar answered Sep 22 '22 02:09

Maurício Linhares