Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Upper Bounded Wildcards/Lower Bounded Wildcards

 
Dante Sparda
Greenhorn
Posts: 19
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

Please pay attention the code below:



Why the actions in Group1 face with compile error while the Group2 works fine ?

I don't know the answer but it seems that only the following actions are possible:

- Remove
- Clear
- Getting the iterator and invoke remove.
- Capturing the wildcard and write elements that you've read from the list.

The following link can be very helpful but I've not found an answer for the question above yet.
Guidelines for Wildcard Use

I appreciate your help
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dante,

Welcome to CodeRanch!

Currently, you have two lists:
1) myList1 - this contains objects of A or its subtype.
2) myList2 - this contains objects of A or its supertype.

Now, the problem is - A can have many subtypes (e.g. X extends A, Y extends A and so on), and hence, myList1 can be a terrible mess of all subtypes of A. To avoid this, Java does not simply allow to add any element to this list.

However, in myList2, all the objects are going to be objects of A (or its supertype) - and hence, myList2 will not be a mess of different objects (that is - objects would be from same hierarchy), and hence, Java allows adding elements in myList2.

So, what's the use of myList1?
Well, you can have a method which accepts a List<? extends A>, and further, while invoking that method, you can pass List<A>, List<B> or List<C> (provided you don't add any element to that list inside the method).

I hope this helps.
 
Dante Sparda
Greenhorn
Posts: 19
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anayonkar,

Thanks for your answer, It is so helpful
 
Himai Minh
Ranch Hand
Posts: 1328
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more note for discussion:
 
Dante Sparda
Greenhorn
Posts: 19
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Himai Minh wrote:One more note for discussion:


I couldn't find any reasonable answer for this
 
Himai Minh
Ranch Hand
Posts: 1328
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I meant was:
 
Dante Sparda
Greenhorn
Posts: 19
Java Netbeans IDE Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Himai Minh wrote:What I meant was:


wow, I got it

It is helpful for the exam

thanks for your help ;)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic