What does the term "limited" mean in java?

I found the word in my textbook in the chapter on collections and generics.

Offer was

"Because the type of objects in the general class is limited, elements can be accessed without casting."

Simply put, can someone explain what this sentence means?

+6
source share
4 answers

When you use a collection without generics, the collection will accept Object , which means everything in Java (and will also give you Object if you try to get any of this):

List objects = new ArrayList(); objects.add( "Some Text" ); objects.add( 1 ); objects.add( new Date() ); Object object = objects.get( 0 ); // it a String, but the collection does not know 

After using generics, you limit the types of data that a collection can store:

 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 

Thus, the limitation is that you force the collection to use only one specific type, and not all, as if you had not defined a common signature.

+7
source
 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 
+2
source

Check out my own answer here.

Since the type of objects in the general class is limited, elements can be accessed without casting.

One of the advantages of using Generic code over a raw type is that you do not need to explicitly return the result to the corresponding type. This is implicitly performed by the compiler using the Type Erasure method.

Suppose we take an 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 is because List was declared to store only a list of integers

+1
source

This means that if you have a common class, such as a collection, of type T , you can only put instances of T

For instance:

 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
source

Source: https://habr.com/ru/post/893470/


All Articles