Reputation: 1
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
Reputation: 66
My proposal an Object-oriented programming :
Account
class : public abstract String getType();
EspecialAccount
as follow :public String getType() { return "EspecialAccount"; }
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
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
Reputation: 2452
You can use instanceof like:
for(int i=0; i<aLista.size(); i++){
if(aLista.get(i) instanceof specialAccounts)
//...
}
Upvotes: 1
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