I was going through one of the examples in the K&B SCJP5 book.
Here is the code that i tried out:
In the TestGenerics class i call the method in the Dog class, the code is:
It does not compile as argument passed to the method does not match that with the method signature as in the Dog class.
And hence the error:
D:\JAVA\shekhar java\sudipto nw\TestA.java:35: addAnimal(java.util.List<Dog> in Dog cannot be applied to (java.util.List<capture of ? super Dog> ((Dog)dogList.get(0)).addAnimal(dogList);// this line does not compile ^ 1 error
My question is the List dogList is of what generic type, as passing the list to the method in Dog class resulted in error and so it is not of type <Dog>. Please explain...
First of all, you broke the generics. DogList is not a list of dogs -- it's a list of some unknown type that could be either dogs, animal, or objects. In this code, you casted the return type to Dog. The reason you probably did it is because the compiler complained.
Forcing the type when the compiler complains is not a good idea. If you are going to cast when you disagree with the compiler, then why bother using generics?
But to answer your question....
Again, dogList is not a list of dogs -- it's a list of some unknown type that could be either dogs, animal, or objects. The addAnumal() method of the Dog class requires a list of dogs, it can't accept a list of animals, or a list of objects. Since, dogList may not be a list of dogs, the compiler is complaining again.
Henry [ December 16, 2008: Message edited by: Henry Wong ]
I understand what you say but how did i break Generics?
I am sorry I could not understand you... Please explain....
Basically, with Generics, you are asking that the Java compiler type check everything for you. But you had to cast the return for the collection to Dog.
Why? Because after the type checking, the Java compiler determined that it can only guarrantee that it is of an object type that is returned. You disagreed and casted it to Dog. BTW, there is nothing wrong with *not* using generics. If you don't agree with the type checking, then don't use generics. To use it, but cast when you don't agree is silly.
Originally posted by Sudipto Shekhar: I think I did not understand the purpose of generics(from the usage of the generics in the classes I showed in the previous posts). Please guide me if I am wrong somewhere.
As mentioned, there is nothing wrong with not using generics. The purpose of generics is to help you at runtime, by doing type checks are compile time.
But if it's too difficult to apply to your application. Or if you have to cast, because you disagree with the type checks, it may be best to just not use generics.