循环查找数组列表并将与两个数组列表匹配的值添加到新列表中

时间:2018-11-24 12:29:45

标签: java arraylist

我正在尝试制作一个使客户的兴趣与假期相关的程序,我有一个假期的数组列表和一个针对客户兴趣的字符串数组列表,我想创建一个新的数组列表,添加两个中都包含的所有元素。这就是我所拥有的,但是它带有一个空指针异常,我在哪里出错了? 调试器指向不相交的位置,并指向“ 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));
    }
}

1 个答案:

答案 0 :(得分:0)

在使用holidays之前,您需要对其进行初始化;在matchedHolidays中向其添加值之前,findHolidayMatch

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