0

Here is my Java Code:

    package com.Pramithas.Project;

    import java.util.ArrayList;
    import java.util.List;

    abstract class Animal{
        public abstract void check();
    }

    class Dog extends Animal{
        public void check(){
            System.out.println("From inside Dog");
        }
    }

     public class AnimalDoctor {

        public void checkAnimals(List<? super Dog>animals){
            animals.add(new Dog());

            for(Animal a:animals){
                // Here is the problem. I also tried (Dog d:animals),
                //but it did not work either. 
            }
        }

     public static void main(String[] args) {

             List<Animal>myList=new ArrayList<Animal>();
             myList.add(new Dog());
             myList.add(new Dog());
             new AnimalDoctor().checkAnimals(myList);
        }
    }

Inside the method checkAnimals() I am trying to access the contents of the list animals using enhanced for statement. But having the problem. Please help me out.

John
  • 2,820
  • 3
  • 30
  • 50
hermit
  • 1,048
  • 1
  • 6
  • 16

3 Answers3

1

Your list could contain Objects, Animals and Dogs, so you would need to write for(Object o : animals)

Alternative you could define your list as List<? extends Animal>, which would make sure only Animals are in your list.

? super X means "everything that is a superclass of X (including X itself)"

? extends X means "everything that extends X (including X itself"

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
1

When you do <? super Dog>, it tells the compiler to accept any super type of Dog up till Object and any Interfaces.

And it is meant to be used only as a Consumer, read about PECS.

So, ideally you shouldn't be trying to read from a <? super X> object, only add values to that.

But if you still want to read, you need to assign it as an Object.

for(Object a3:animals){

}
Community
  • 1
  • 1
Codebender
  • 14,221
  • 7
  • 48
  • 85
1

The way you've defined your list (List<? super Dog>) denotes a list, where you can add elements to, but cannot get elements from.

From what I can see, the checkAnimals() method is interested in both reading from and writing to the list, so you have to change it to:

public void checkAnimals(List<Animal> animals){
    animals.add(new Dog());

    for(Animal a : animals){

    }
}
Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147