• An example problem of Generic types


     

    The following code has a compilation errors. It is confusing because you think somewhere to find the problem.

    import java.util.*;
    abstract class Animal{
        public abstract void checkup();
    }
    class Dog extends Animal{
        public void checkup(){
            System.out.println("Dog checkup");
        }
    }
    class Cat extends Animal{
        public void checkup(){
            System.out.println("Cat checkup");
        }
    }
    class Bird extends Animal{
        public void checkup(){
            System.out.println("Bird checkup");
        }
    }
    public class AnimalDoctorGeneric {
        private void checkAnimals(ArrayList<Animal> animals){
            for(Animal a : animals){
                a.checkup();
            }
        }
        private void addAnimals(List<Animal> animals){
            animals.add(new Dog());
        }
        public static void main(String [] args){
            List<Animal> animals = new ArrayList<Animal>();
            animals.add(new Dog());
            animals.add(new Dog());
            AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
            doc.addAnimals(animals);
            doc.checkAnimals(animals);// error here!!!!
            //doc.checkAnimals((ArrayList<Animal>) animals); this line is the correct code
            //to use checkAnimals method, the argument has to be correct type. 
            //System.out.println(animals.get(1) + " " + animals.get(2));
        }
    }

    To fix the code the easiest way is to cast animals to ArrayList. So to change line 36 to:
    doc.checkAnimals((ArrayList) animals);

    The reason is that ArrayList class implements List interface, they are different, List need to be cast to ArrayList in order to satisfy method checkAnimals(ArrayList animals).

  • 相关阅读:
    The 2019 China Collegiate Programming Contest Harbin Site A
    牛客练习赛15
    Wannafly挑战赛13-C
    Wannafly挑战赛13-D
    Subsequence Counting
    Minimize the error
    Educational Codeforces Round 42 (Rated for Div. 2)
    K-th Number
    Wannafly挑战赛13-E
    Minimum spanning tree for each edge
  • 原文地址:https://www.cnblogs.com/hephec/p/4556727.html
Copyright © 2020-2023  润新知