【问题标题】:Looping for array lists and adding values which match two array lists into a new one循环数组列表并将匹配两个数组列表的值添加到新列表中
【发布时间】:2018-11-24 12:29:44
【问题描述】:

我正在尝试制作一个程序,将客户的兴趣与假期的各个方面相匹配,我有一个假期数组列表和一个客户兴趣的字符串数组列表,我想创建一个新的数组列表添加两者中包含的所有元素。这就是我所拥有的,但它出现了一个空指针异常,有什么想法我出错了吗? 调试器指向不相交并位于“int c1size = c1.size();” 相关代码部分...

主要...

ClientExt1 marina = new ClientExt1("Marina",14321,"marina.calder1@btinternet.com");
ArrayList<String> interests = new ArrayList<>();
interests.add("History");
interests.add("Music");
marina.setInterests(interests);
holidaySeller.getHolidayMatches(marina);

客户...

public class ClientExt1 {

private String name;
private int id;
private String email;
private HolidayExt1 holidayBooked;
private ArrayList<String> interests;

public ClientExt1(String name, int id, String email){
    this.name=name;
    this.id=id;
    this.email=email;


}

public void setInterests(ArrayList interests) {
    this.interests=interests;
}

public ArrayList<String> getInterests(){
    return interests;

公司类...

public class CompanyExt1 {
    protected ArrayList<StaffExt1> staffMembers;                  
    protected ArrayList<HolidayExt1> holidays;
    protected ArrayList<GuideExt1> holidayGuides;
    protected ArrayList<AdventureExt1> adventureHolidays;
    protected ArrayList<CultureExt1> cultureHolidays;
    private ArrayList<String> matchedHolidays;


    public ArrayList<String> findHolidayMatch(ClientExt1 client) {
        ArrayList interests = client.getInterests();
        int i;
        for (i = 0; i < holidays.size() && i< interests.size(); i++) {
            if (!Collections.disjoint(holidays.get(i).getAspects(), interests)) {
                matchedHolidays.add(holidays.get(i).getName());

            }
        }
        return matchedHolidays;
    }

    public void getHolidayMatches(ClientExt1 client){
        System.out.println(client.getName() + ", the holidays recommended to you based on your interests from this company are:" + findHolidayMatch(client));
    }
}

【问题讨论】:

  • 添加更多代码。
  • 调试器指向与 Collections 不相交的地方,并且位于“int c1size = c1.size();”

标签: java arraylist


【解决方案1】:

您需要在使用之前初始化holidays 和在findHolidayMatch 中向其添加值之前初始化matchedHolidays

我实际上会将matchedHolidays 设为局部变量而不是类成员,因为它仅在findHolidayMatch 方法的范围内使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2017-07-29
    • 2015-11-28
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多