1

I have an ArrayList containing objects derived from an abstract class, is there a way to return the an array list of the abstract class type then, using polymorphism, be able to reference the origin object?

The only way I can see of doing this is to create an ArrayList of the abstract class type, then copy the elements from the original ArrayList into this, but I don't want copies.

1
  • 2
    Post your code, and tell us precisely what you would like to do that is not possible with what you have. Commented Nov 6, 2015 at 15:21

1 Answer 1

2

Let's suppose your concrete class is Integer and your abstract class, Number.

If you are willing to receive a result cast as a List<Number> instead of an ArrayList<Number> (a good practice anyway), you can do something like the following:

List<Integer> listOfConcrete = new ArrayList<>(); // your actual list
List<Number> listOfAbstract = listOfConcrete.stream()
  .map(n -> (Number) n)
  .collect(Collectors.toList());

You need the explicit cast in the map() call so that the casting is performed properly.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, that was quick, I used your example and it works great, my method looks like this: public ArrayList<clsPoll> alobjGetPollSchedule() { retrurn (ArrayList<clsPoll>)malobjPollSchedule.stream().map(n -> (clsPoll)n).collect(Collectors.toList()); }
No, you don’t need the explicit cast in map. Actually, you don’t need the map step at all. listOfAbstract = listOfConcrete.stream().collect(Collectors.toList()); is sufficient. But you don’t even need Java 8 to copy a list: List<Number> listOfAbstract = new ArrayList<>(listOfConcrete); works as well.
And if the goal is to consume the List<Integer> as numbers, maybe all is needed is List<? extends Number> listOfAbstract = listOfConcrete;, which doesn't need any copy. But the OP should really clarify, so that we know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.