0

Is it possible for an ArrayList to return a list of superclass objects?

For example:

Class B extends Class A.

I have an ArrayList of Class B.

How do I use Java 8 to return an ArrayList of objects of Class A?

Eg:

class ClassA {}
class ClassB extends ClassA{}

I have a list of ClassB called classBList. I want to get a list of ClassA objects.

List <ClassA> classAList = new ArrayList <ClassA> (classBList);

But I am still getting ClassB in classAList.

Please help. Thanks.

Shazam
  • 105
  • 1
  • 7
  • You already have one; a list of B objects is a list of A objects, because all B objects are A objects. Perhaps you could edit the question to be more specific about what you are trying to achieve, ideally with a code example. – kaya3 Nov 24 '19 at 00:39
  • Edited. Is it possible? – Shazam Nov 24 '19 at 01:20
  • Unless `ClassA implements List` then `ClassA` is certainly not assignable to `List`. But this isn't enough code for me to work out what you're trying to do; please write a minimum reproducible example. https://stackoverflow.com/help/minimal-reproducible-example – kaya3 Nov 24 '19 at 01:22
  • As long as you don't expect a client to add something to the list after calling the method your're working on, you can declare it as `public List extends ClassA> body()`, which allows returning a `List`. – Izruo Nov 24 '19 at 01:31
  • I have edited with codes. Please help. Thanks. – Shazam Nov 24 '19 at 01:42

1 Answers1

0

If I understand the question correctly, you have a list of objects of runtime type ClassB and want a list of objects of runtime type ClassA.

Consider:

ClassB b = new ClassB();
ClassA a = b

Here b and a refers to the same instance. An instance of ClassB.

If we really wanted to change the runtime type, we'd need to create a new object. Assuming an appropriate constructor:

ClassA b = new ClassB();
ClassA a = new ClassA(a);

To apply that to a list, I think:

List<ClassA> as = bs.stream()
    .map(ClassA::new)
    .toCollection(Collectors.toCollection(ArrayList::new));

Or, more readably but less impressively:

List<ClassA> as = new ArrayList<>() {
for (ClassB b : bs) {
    as.add(new ClassA(b);
}

However, in general a class should be either a leaf (effectively final) or abstract.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305