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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With