Forums Register Login

Generics Doubts

+Pie Number of slices to send: Send
Hi All,
Can anyone explain me about generics in java? I've quite comfortable with normal generics concept and when the generics with wild character comes I going to hell.
mainly the three topics I've alot of questions after read more articles about this.
+Pie Number of slices to send: Send
Check the link Generics
Go through it and then if you have any specific question then ask.
+Pie Number of slices to send: Send
You must have to read the chapter 7 of K & B book atleast 2 or 3 times.
Then you will get to understand the generics
+Pie Number of slices to send: Send
And sorry I didnot noticed earlier

Welcome To JavaRanch......
+Pie Number of slices to send: Send
Hi,

Thanks for giving a nice document/link to understand basics of generics. But still I've doubts on wild characters with extends and super. Actually what is mean? when and where I need to use these?

Kindly give me a nice simple example of these to understand easily.
+Pie Number of slices to send: Send
There are a few such questions in ExamLab on Generics

specially about

i) <? extends B>
ii) <? super Animal>

explaining why we cannot add anything to the i) one
and what can we add to the ii)

You can read the explanation from there.
+Pie Number of slices to send: Send
Generic is only a compile time concept.....if you are clear with the basics of generic...then think now like you are a compiler.
void foo(List<? extends Animal> list){}

it means you can add anything which passes IS-A relationship with Animal like Cat,Dog.

In this method the compiler only knows about the Animal. Anything which you want, you can only do with the Animal.so,you can add only Animal.

void foo(List<? extends Animal> list){
list.add(new Animal()); //compile time error
}

thing what happens when we pass the Dog list...
List<Dog> d;
foo(d);

then the jvm will throw an exception-ClassCastException.because in Dog you can't add an Animal...so,to avoid these kind of excetion...compiler does not allow you to add anything...

and try to understand super like this
Yup, yup, yup. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 741 times.
Similar Threads
generics
Generics
Generics...
Generics question
Doubt with generics
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 15, 2024 23:01:28.