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

I need to add an element and print in list

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have using the following function now i want to add an element in the list which is working fine but bow i want to print the elements of the list As well. Can someone please let me know how can i print the list using for each loop with in the same function after adding an element?

Animals is the super class of Dogs.


public void check2(List<? super Dogs> list){
list.add(new Dogs());
for(Animals a:list)
a.checkup();
}
 
Campbell Ritchie
Sheriff
Pie
Posts: 50246
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the Code button. Please put {} round the body of the for-each loop.

How about System.out.println(a);
 
Campbell Ritchie
Sheriff
Pie
Posts: 50246
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you add an element to a List<? super Anything>? I don't think you can.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can add an element we can't add it for <? extends Dogs>

it is giving error for traversing....
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
john sal wrote:We can add an element we can't add it for <? extends Dogs>

But what you can't then do is assume everything in list is an Animal. Your signature would allow you to pass a List<Object> in - what's going to happen then? So your for-loop is wrong.

 
Campbell Ritchie
Sheriff
Pie
Posts: 50246
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hadn't noticed that. Passing a List<Animal> might be better, as you imply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic