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
Joined: Oct 13, 2005
Posts: 32654
4
posted
0
Please use the Code button. Please put {} round the body of the for-each loop.
How about System.out.println(a);
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
4
posted
0
Can you add an element to a List<? super Anything>? I don't think you can.
john sal
Ranch Hand
Joined: Jul 30, 2010
Posts: 92
posted
0
We can add an element we can't add it for <? extends Dogs>
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
Joined: Oct 13, 2005
Posts: 32654
4
posted
0
I hadn't noticed that. Passing a List<Animal> might be better, as you imply.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: I need to add an element and print in list