继承一个抽象类的多种类型的ArrayList

我创建了一个account抽象类,它是另外 3 个不同帐户类的超类。


然后在一个manageAccount类中我必须创建一个存储帐户类的 ArrayList。在这个类中,我有一个方法应该找到特定类型的类,例如,它返回EspecialAccount数组列表中的每个类。我的 arrayList 是类型Account,我不知道如何添加继承它的类。是否可以?


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?

        }

    }

我是JAVA初学者,请多多指教。


明月笑刀无情
浏览 246回答 4
4回答

拉丁的传说

过滤掉就可以了&nbsp;ArrayList<Account>&nbsp;accounts;&nbsp;all&nbsp;accounts List<SpecialAccount>&nbsp;filteredAccounts=&nbsp;sccounts.stream().filter(SpecialAccount.class::isInstance).collect(Collectors.toList());

森林海

您可以使用instanceof,例如:for(int i=0; i<aLista.size(); i++){      if(aLista.get(i) instanceof specialAccounts)        //...}

沧海一幻觉

我的建议是面向对象编程&nbsp;:向类添加一个抽象方法Account:public abstract String getType();实现该方法如下EspecialAccount:public&nbsp;String&nbsp;getType()&nbsp;{&nbsp;return&nbsp;"EspecialAccount";&nbsp;}然后,致电searchSpecialAccounts():public String searchSpecialAccounts() {&nbsp; for(Account acc : aLista){&nbsp; &nbsp; if(acc.getType().equals("EspecialAccount")) {&nbsp; &nbsp; &nbsp; // acc is of searchType type, great !&nbsp; &nbsp; }&nbsp; }}如果要指定 的默认值,getType()可以在抽象类上实现它,然后仅为特殊帐户类重写它。

慕的地8271018

检查 searchSpecialAccounts() 的返回类型;package com;import java.util.ArrayList;import java.util.List;public class ManageAccounts {&nbsp; &nbsp; ArrayList<Account> aList = new ArrayList<>();&nbsp; &nbsp; List<SpecialAccounts> specialAccountsList = new ArrayList<>();&nbsp; &nbsp; public List<SpecialAccounts> searchSpecialAccounts(){&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0; i<aList.size(); i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //how can I search in the arrayList all of the specialAccounts?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(aList.get(0) instanceof SpecialAccounts) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; specialAccountsList.add(specialAccountsList.get(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return specialAccountsList;&nbsp; &nbsp; }}class SpecialAccounts extends Account {}class Account {}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java