4 回答

TA貢獻1789條經驗 獲得超8個贊
過濾掉就可以了
ArrayList<Account> accounts; all accounts List<SpecialAccount> filteredAccounts= sccounts.stream().filter(SpecialAccount.class::isInstance).collect(Collectors.toList());

TA貢獻2011條經驗 獲得超2個贊
您可以使用instanceof,例如:
for(int i=0; i<aLista.size(); i++){
? ? ? if(aLista.get(i) instanceof specialAccounts)
? ? ? ? //...
}

TA貢獻1824條經驗 獲得超5個贊
我的建議是面向對象編程 :
向類添加一個抽象方法
Account
:public abstract String getType();
實現該方法如下
EspecialAccount
:
public String getType() { return "EspecialAccount"; }
然后,致電
searchSpecialAccounts()
:
public String searchSpecialAccounts() {
for(Account acc : aLista){
if(acc.getType().equals("EspecialAccount")) {
// acc is of searchType type, great !
}
}
}
如果要指定 的默認值,getType()可以在抽象類上實現它,然后僅為特殊帳戶類重寫它。

TA貢獻1796條經驗 獲得超4個贊
檢查 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 {
}
添加回答
舉報