Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

inheritance - How to add ArrayList<SuperClass> to ArrayList<SubClass>

I have an ArrayList of the type of the super class. This ArrayList contains objects of the subclasses of the superclass. I want to copy the objects to an ArrayList . I made a check to the ArrayList to find which objects are of the type of subclass specified to my new ArrayList. But Java doesn`t let me do this.(Cant convert from SuperClass to SubClass). The subclass contains some methods that are not inherited from the superclass. So , i want to extract the objects of this subclass to an other arraylist to do some calculations. The code line looks something like this:

 for(int i = 0; i < ArrayList<SuperClass>.size(); i++)
        {
            if(ArrayList<SuperClass>.get(i).getType().equals("Something"))
            {
                ArrayList<SubClass>.add(ArrayList<SuperClass>.get(i));
            }
        }

So i get a complie error that doesnt let me do this, while i know the specific object is the type of subclass.

question from:https://stackoverflow.com/questions/65641544/how-to-add-arraylistsuperclass-to-arraylistsubclass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...