Guilherme182
Guilherme182

Reputation: 1

ArrayList of multiple types that inherits one abstract class

I made one account abstract class that is the super class of another 3 different account classes.

Then in a manageAccount class I have to create an ArrayList that stores account classes. In this class I have a method that should find a specific type of class, for example, it returns every EspecialAccount classes in the arraylist. My arrayList is of type Account and I can't see how I can add the classes that inherit it. Is it possible?

public class ManageAccounts {

    ArrayList<Account> aList = new ArrayList();


    public String SearchSpecialAccounts(){
        for(int i=0; i<aLista.size(); i++){
            //how can I search in the arrayList all of the specialAccounts?
        }
    }

I'm a beginner at JAVA, please be nice.

Upvotes: 0

Views: 256

Answers (4)

ludovjb
ludovjb

Reputation: 66

My proposal an Object-oriented programming :

  1. add an abstract method to Account class : public abstract String getType();
  2. implements this method in EspecialAccount as follow :
public String getType() { return "EspecialAccount"; }
  1. then, call searchSpecialAccounts() :
public String searchSpecialAccounts() {
  for(Account acc : aLista){
    if(acc.getType().equals("EspecialAccount")) {
      // acc is of searchType type, great !
    }
  }
}

If you want to specify a default value for getType(), you can implement it on the abstract class and then override it for special accounts classes only.

Upvotes: 0

madhepurian
madhepurian

Reputation: 271

check the return type of searchSpecialAccounts();

package com;

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

public class ManageAccounts {

    ArrayList<Account> aList = new ArrayList<>();

    List<SpecialAccounts> specialAccountsList = new ArrayList<>();
    public List<SpecialAccounts> searchSpecialAccounts(){
        for(int i=0; i<aList.size(); i++){
            //how can I search in the arrayList all of the specialAccounts?
            if(aList.get(0) instanceof SpecialAccounts) {
                specialAccountsList.add(specialAccountsList.get(i));
            }
        }
        return specialAccountsList;
    }
}

class SpecialAccounts extends Account {

}
class Account {

}

Upvotes: 0

Nehorai Elbaz
Nehorai Elbaz

Reputation: 2452

You can use instanceof like:

for(int i=0; i<aLista.size(); i++){
      if(aLista.get(i) instanceof specialAccounts)
        //...
}

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32507

Just filter it out

 ArrayList<Account> accounts; all accounts

List<SpecialAccount> filteredAccounts= sccounts.stream().filter(SpecialAccount.class::isInstance).collect(Collectors.toList());

Upvotes: 2

Related Questions