为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

明月笑刀无情 2023-08-16 16:12:54
我创建了一个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初学者,请多多指教。
查看完整描述

4 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

过滤掉就可以了

 ArrayList<Account> accounts; all accounts

List<SpecialAccount> filteredAccounts= sccounts.stream().filter(SpecialAccount.class::isInstance).collect(Collectors.toList());
查看完整回答
反对 回复 2023-08-16
?
森林海

TA贡献2011条经验 获得超2个赞

您可以使用instanceof,例如:

for(int i=0; i<aLista.size(); i++){

      if(aLista.get(i) instanceof specialAccounts)

        //...

}


查看完整回答
反对 回复 2023-08-16
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

我的建议是面向对象编程 :

  1. 向类添加一个抽象方法Accountpublic abstract String getType();

  2. 实现该方法如下EspecialAccount

public String getType() { return "EspecialAccount"; }
  1. 然后,致电searchSpecialAccounts()

public String searchSpecialAccounts() {

  for(Account acc : aLista){

    if(acc.getType().equals("EspecialAccount")) {

      // acc is of searchType type, great !

    }

  }

}

如果要指定 的默认值,getType()可以在抽象类上实现它,然后仅为特殊帐户类重写它。


查看完整回答
反对 回复 2023-08-16
?
慕的地8271018

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 {


}


查看完整回答
反对 回复 2023-08-16
  • 4 回答
  • 0 关注
  • 245 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号