aspose file tools*
The moose likes Java in General and the fly likes I need to add an element and print in list Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "I need to add an element and print in list" Watch "I need to add an element and print in list" New topic
Author

I need to add an element and print in list

john sal
Ranch Hand

Joined: Jul 30, 2010
Posts: 93
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: 40052
    
  28
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: 40052
    
  28
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: 93
We can add an element we can't add it for <? extends Dogs>

it is giving error for traversing....
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4490
    
    8

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: 40052
    
  28
I hadn't noticed that. Passing a List<Animal> might be better, as you imply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I need to add an element and print in list